JPA:如何处理多个实体

时间:2016-11-08 12:44:07

标签: java hibernate jpa spring-boot spring-data

我是JPA的新手,对如何处理权限有疑问。在我的情况下,我有3个实体:用户,组和事件。

事件始终属于某个组。这意味着有一个OneToMany-Relation。用户可以订阅多个组,这意味着存在ManyToMany-Relation。现在是我遇到麻烦的部分。用户还可以订阅多个事件,这意味着还存在ManyToMany-Relation。

enter image description here 代码:

用户

@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;
    ...
}

现在我的问题。如何在我的Group-Entity中有一个包含已定位事件的列表,该列表取决于用户实体? 我的目标是这样的:

user.getSubscribedGroups().get(0).getSubscribedEvents();

1 个答案:

答案 0 :(得分:1)

试试这个:

@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;

...
}