两个实体上的JPA / Hibernate Bidirectional Set <object>

时间:2017-03-25 20:19:54

标签: java hibernate jpa

public class Event {
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<User> users = new HashSet<>();
}

public class User {
    @OneToMany
    private Set<Event> events = new HashSet<>();
}

我如何建立从用户实体到事件的双向链接?

事件实体创建一个名为event_users的数据透视表。

1 个答案:

答案 0 :(得分:1)

您必须使用@ManyToMany映射:

public class Event {
    @ManyToMany(cascade = CascadeType.ALL, mappedBy="events")
    private Set<User> users = new HashSet<>();
}

public class User {
    @ManyToMany
    @JoinTable(
      name="event_users",
      joinColumns=@JoinColumn(name="user_ID", referencedColumnName="ID"),
      inverseJoinColumns=@JoinColumn(name="event_ID", referencedColumnName="ID"))
    private Set<Event> events = new HashSet<>();
}

我假设两个表的ID都称为ID,并且链接表包含user_idevent_id

用户将是这里关系的拥有者。