whileFalse
whileFalse

Reputation: 85

JPA: How to handle multiple Entities

I'm new to JPA and have a question about how to handle entitites. In my case I have 3 Entities: User, Group and Event.

An event always belongs to a group. Which means there is a OneToMany-Relation. A user can subscribe to multiple groups which means there is a ManyToMany-Relation. Now the part where I'm having troubles. A user can also subscribe to multiple events which means that there is also a ManyToMany-Relation.

enter image description here As code:

User

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

Group

@Entity
public class Group {

    @Id
    @GeneratedValue
    private Integer id;

    @OneToMany(???)
    private List<Event> events;
    ...
}

Now my problem. How can I have a list with susbcribed events in my Group-Entity which depends on the User-Entity? My goal would be something like this:

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

Upvotes: 2

Views: 2398

Answers (1)

Merve Sahin
Merve Sahin

Reputation: 1048

Try this :

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

...
}

Upvotes: 1

Related Questions