Reputation: 4743
I am referring to the example at - http://viralpatel.net/blogs/hibernate-many-to-many-annotation-mapping-tutorial/ Employees can attend many Meetings and Meetings can be attended by many Employees.
Let the owning class be Employee. The many to many mapping code inside Employee will be -
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="EMPLOYEE_MEETING",
joinColumns={@JoinColumn(name="EMPLOYEE_ID")},
inverseJoinColumns={@JoinColumn(name="MEETING_ID")})
private Set<Meeting> meetings = new HashSet<Meeting>();
I looked at several other examples and documentation, but I am still not sure how this works. I don't think I fully understand what joinColumns and inverseJoinColumns do.
joinColumns={@JoinColumn(name="EMPLOYEE_ID")}
- Does this line only tell hibernate
that Employee id of employee joins employee id of the mapping table ?
inverseJoinColumns={@JoinColumn(name="MEETING_ID")})
? Does this line only tell hibernate to join Employee id to the Meeting_Id column in the link table ?
Upvotes: 2
Views: 276
Reputation: 6540
What the actual annotation is saying is that Hibernate should create an intermediate join table. One column of this table should map to the column on your Employee
table called Employee_ID
(that's your joinColumns
parameter), and the other column should map to the column on your Meeting
table called Meeting_ID
(that's your inverseJoinColumns
parameter).
The joinColumns
parameter should specify the PK of the owning entity (in this case your Employee object), while the inverseJoinColumn
specifies the PK of the non-owning entity.
Note that you don't always have to just specify your join columns as PK's, but it makes sense because uniqueness is enforced and its kind of the point of a PK. You can also have multiple join columns forming a composite key on either side of the relationship within the join table.
You seem to have a handle on how the relationships are set up but I'll say this for the benefit of people coming here from Google. In a bidirectional relationship you have to specify which side of the relationship 'owns' the relationship. While you can have a bidirectional cascade as well, you usually only access the non-owning object through the owning one. So you don't generally access a Meeting
object directly, you access it through a Employee
object. This becomes more important in a uni-directional relationship but it can cause a few problems in a bidirectional relationship in determining what you want to cascade.
For example, if you decide that if you delete a Meeting
, you don't want the deletion to cascade to the join table, you need to change your CascadeType
in your Meeting
class.
If you want me to expand on my explanation please let me know.
Upvotes: 3