2017-09-04 44 views
1

我有休眠和JSON的問題,當我使用多對多同一類,我得到遞歸Hibernate的多對多使用同一類,無法寫入JSON:無限遞歸

import org.hibernate.annotations.GenericGenerator; 

import javax.persistence.*; 
import java.util.Set; 
import java.util.UUID; 

@Entity 
public class AssistantGraphVertex { 

    @Id 
    @GeneratedValue(generator = "uuid") 
    @GenericGenerator(name = "uuid", strategy = "uuid2") 
    private UUID uuid; 

    @ManyToOne 
    private AssistantGraphs assistantGraphs; 

    private String name; 
    private String description; 

    @ManyToMany(cascade = {CascadeType.ALL}) 
    @JoinTable(name = "assistant_graph_edge", 
      joinColumns = { @JoinColumn(name = "parent_uuid") }, 
      inverseJoinColumns = { @JoinColumn(name = "child_uuid") } 
    ) 
    private Set<AssistantGraphVertex> parents; 

    @ManyToMany(mappedBy = "parents") 
    private Set<AssistantGraphVertex> children; 

    public UUID getUuid() { 
     return uuid; 
    } 

    public void setUuid(UUID uuid) { 
     this.uuid = uuid; 
    } 

    public AssistantGraphs getAssistantGraphs() { 
     return assistantGraphs; 
    } 

    public void setAssistantGraphs(AssistantGraphs assistantGraphs) { 
     this.assistantGraphs = assistantGraphs; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 

    public Set<AssistantGraphVertex> getChildren() { 
     return children; 
    } 

    public void setChildren(Set<AssistantGraphVertex> children) { 
     this.children = children; 
    } 

    public Set<AssistantGraphVertex> getParents() { 
     return parents; 
    } 

    public void setParents(Set<AssistantGraphVertex> parents) { 
     this.parents = parents; 
    } 
} 

問題的樣子此:

未能寫入HTTP消息:org.springframework.http.converter.HttpMessageNotWritableException:無法寫入JSON:無限遞歸(的StackOverflowError);

我想只收到關於其父母和孩子的一類信息,但對於下一個嵌套類,我不需要這些信息,這怎麼能更好地實現?

+0

這是https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue?rq=1的副本? –

+0

@JackFlamp沒有人,我不想忽略這個json fild,請讀取問題,我需要關於兒童和父母的信息 –

回答

2

,你可以簡單地忽略序列化的一面起訴@JsonIgnore

@JsonIgnore 
@ManyToMany(cascade = {CascadeType.ALL}) 
@JoinTable(name = "assistant_graph_edge", 
     joinColumns = { @JoinColumn(name = "parent_uuid") }, 
     inverseJoinColumns = { @JoinColumn(name = "child_uuid") } 
) 
private Set<AssistantGraphVertex> parents; 

@JsonIgnore 
@ManyToMany(mappedBy = "parents") 
private Set<AssistantGraphVertex> children; 

,也可以使用@JsonIdentityInfo將在系列化這將第二級創建休眠參考打破循環

@Entity 
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id") 
public class AssistantGraphVertex { 

欲瞭解更多詳情檢查這link

+0

我不想忽略這個變量,我想獲取關於它們的信息,但僅限於第一個元素 –

+0

@AndrewSergeev然後去第二個建議,它會實現你的目標 –

+0

第二個建議工作,謝謝你的鏈接,我會去讀),因爲我不明白如何@JsonIdentityInfo工作 –