我是JPA的新手,有一个关于如何处理实体的问题。在我的例子中,我有3个实体:用户、组和事件。
一个事件总是属于一个组。这意味着有一个OneToMulti-Relation。一个用户可以订阅多个组,这意味着有一个ManyToMulti-Relation。现在我遇到麻烦的部分。一个用户也可以订阅多个事件,这意味着也有一个ManyToMulti-Relation。
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
@Embedded
@OneToOne
@JoinColumn(name = "company_location")
private CompanyLocation companyLocation;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "user_group_subscriptions",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"))
private List<Group> subscribedGroups;
...
}
@Entity
public class Group {
@Id
@GeneratedValue
private Integer id;
@OneToMany(???)
private List<Event> events;
...
}
现在我的问题是。我如何在我的组实体中列出一个依赖于用户实体的可疑事件列表?我的目标是这样的:
user.getSubscribedGroups().get(0).getSubscribedEvents();
试试这个 :
@Entity
public class Event{
@Id
@GeneratedValue
private Integer id;
@ManyToOne
@JoinColumn(name = "your_column")
private Group group;
@ManyToMany
@JoinTable(....)
private List<User> users;
...
}
@Entity
public class Group {
@Id
@GeneratedValue
private Integer id;
@OneToMany(mappedBy = "group")
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private List<Event> events;
...
}