Ali
Ali

Reputation: 267049

How to map one-to-many connection between two entities using a 3rd table, in Hibernate?

I have two entities, User and Event. Each event can have multiple users associated with it, so its a one to many between Event and User.

The way its being stored in the database, is that I have 3 tables, user, event, and event_user. event_user contains 3 fields, id, eventId, userId. So I can do a query like select userId from event_user where eventId = ? to get all the users which are associated with the event.

My question is, how can I map this relationship between the events and users in Hibernate, to get it to auto save/load the users associated with the event? I want to have the following field in the Event class:

Set<User> users = new HashSet<>();

and have hibernate auto load / save the users to this set.

How can I map this (using annotations)?

Upvotes: 1

Views: 779

Answers (2)

sanbhat
sanbhat

Reputation: 17622

Hibernate doc on the Bidirectional mapping using annotations should help

Basically you need to do something like this

@Entity
public class User implements Serializable {
    @ManyToMany(
        targetEntity=org.hibernate.test.metadata.manytomany.Event.class,
        cascade={CascadeType.ALL}
    )
    @JoinTable(
        name="USER_EVENT",
        joinColumns=@JoinColumn(name="USER_ID"),
        inverseJoinColumns=@JoinColumn(name="EVENT_ID")
    )
    public Set<Event> getEvents() {
        return events;
    }
    ...
}              
@Entity
public class Event implements Serializable {
    @ManyToMany(
        cascade = {CascadeType.ALL},
        mappedBy = "events",
        targetEntity = User.class
    )
    public Set<User> getUsers() {
        return users;
    }
}   

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Use the @ManyToMany annotation.

class Event{

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "EVENT_USER", 
               joinColumns = { @JoinColumn(name = "EVENT_ID") }, 
               inverseJoinColumns = { @JoinColumn(name = "USER_ID") })
    private Set<Users> users = new HashSet<Users>();

}

For more information on many to many associations in JPA check out this video tutorial at my blog.

Upvotes: 1

Related Questions