简体   繁体   English

休眠中的多对多自引用关联

[英]many-to-many self-referencing association in hibernate

I want to do this: 我想做这个:

Person <--Many-to-many---> Person 人<-多对多->人

I want to have a relation where one person can have many (more than one) parents and one parent can have many childs (more then one) 我想建立一种关系,一个人可以有很多(多于一个)父母,而一个父母可以有很多孩子(多于一个)

My hibernate mapping 我的休眠映射

@Entity
class Person{

    @Id
    @Column
    long id;

    @Column
    String name;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "Person_Parent", 
      joinColumns={ @JoinColumn(name = "parent_ID") },
      inverseJoinColumns = { @JoinColumn(name = "child_ID")})
    private Set<Person> parent = new HashSet<Person>();

    @JsonIgnore
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "Person_Parent", 
      joinColumns={ @JoinColumn(name = "child_ID") },
      inverseJoinColumns = { @JoinColumn(name = "parent_ID")})
    private Set<Person> child = new HashSet<Person>();
}

Is this mapping correct? 这个映射正确吗? how to make this relation bidirectional. 如何使这种关系是双向的。 so that if I add a Parent. 这样,如果我添加一个父母。 that Parent's child collection should be updated. 父母的孩子的收藏应该被更新。

Without knowing for certain what your issue is, I believe you might be having problems because you have not set a "mappedBy" value for "owning" side of the relationship. 不知道您的问题是什么,我相信您可能会遇到问题,因为尚未为关系的“拥有”一方设置“ mappedBy”值。 Example: 例:

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Person> parent = new HashSet<Person>();

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="parent")
private Set<Person> child = new HashSet<Person>();

(I've removed the @JoinTable for brevity's sake.) Furthermore, you may be interested in a better way of suppressing your JSON serialization by using the following annotations as opposed to @JsonIgnore : (为简便起见,我删除了@JoinTable 。)此外,您可能对通过使用以下注释(而不是@JsonIgnore抑制JSON序列化的更好方法感兴趣:

@JsonBackReference
private Set<Person> parent = new HashSet<Person>();

@JsonManagedReference
private Set<Person> child = new HashSet<Person>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM