2017-03-07 29 views
0

爲了避免無限遞歸,我使用@JsonManagedReference & @JsonBackReference。但是,檢索結果時,我只能從一個方面得到預期結果。Hibernate的多對多雙向 - 雙向@JsonManagedReference&@JsonBackReference

@ManyToMany(cascade = CascadeType.ALL) 
    @JoinTable(name="THIRD_TABLE", 
    joinColumns={@JoinColumn(name="STUDENT_ID")}, 
    inverseJoinColumns={@JoinColumn(name="TEACHER_ID")}) 
    @JsonManagedReference 
    private Set<Teacher> teachers = new HashSet<>(); 

----------- 
    @ManyToMany(mappedBy="teachers") 
    @JsonBackReference 
    private Set<Student> winners = new HashSet<>(); 

讓每個學生的老師很好,但讓每個老師的學生不工作。 JsonBackReference阻止了這一點。

是否有可能有一個字段都註釋和得到它的工作方法有兩種。

回答

0

如果您只想避免遞歸,則可以使用@JsonIdentityInfo。它會爲每個對象生成id,如果重複,則用它的id替換重複的對象。

下面是一個簡單的父/子例如:

@JsonIdentityInfo(generator=IntSequenceGenerator.class) 
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) 
public class Parent { 
    private List<Child> children=new ArrayList<>(); 
    private String name="parent"; 

    public Parent() { 
    super(); 
    children.add(new Child(this,"foo")); 
    children.add(new Child(this,"bar")); 
    } 

    public List<Child> getChildren() { 
    return children; 
    } 

} 
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) 
public class Child { 
    private Parent parent; 
    private String pseudo="toto"; 
    public Child(Parent parent, String pseudo) { 
    super(); 
    this.parent = parent; 
    this.pseudo = pseudo; 
    } 

} 



public class SOJson { 
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { 
    ObjectMapper objectMapper = new ObjectMapper(); 
    Parent object=new Parent(); 
    String json1 = objectMapper.writeValueAsString(object); 
    System.out.println("write parent: "+json1); 
    String json2 = objectMapper.writeValueAsString(object.getChildren().get(0)); 
    System.out.println("write child: "+json2); 

    } 
} 

結果:

write parent: {"@id":1,"children":[{"parent":1,"pseudo":"foo"},{"parent":1,"pseudo":"bar"}],"name":"parent"} 
write child: {"parent":{"@id":1,"children":[{"parent":1,"pseudo":"foo"},{"parent":1,"pseudo":"bar"}],"name":"parent"},"pseudo":"foo"} 

你看,有孩子和父母之間的遞歸,如果去掉@ JsonIdentityInfo你將有一個計算器。

當然,你需要的地方停止你的遞歸,否則你將轉儲數據庫!二者必選其一@jsonIgnore到某處停止你的遞歸或Hibernate4Module上卸載延遲屬性停止遞歸。 (我更喜歡使用兩者)