Brandon Brandon - 3 months ago 11
Java Question

How to map many-to-many List in Hibernate with a Link Table

I would like to map a many-to-many in Hibernate using a link table. I have two classes, Parent and Child class, for example:

public class Parent{

private List<Child> _children;

//...getters and setters

I use a link table (link_table) with three columns
, and
. The database is SQL server and id types are uniqueidentifier. So, I usually use guid for the id fields.

How can you implement this using the
<list />
tag if this is the correct tag to use? Do you know of any good documentation to accomplish this?

I am currently getting a ConstraintViolationException but have not been able to find any good documentation or examples of this.

I think a main issue is: how to specify the
to be automatically generated in the link table.


I don't think that it is possible (or necessary) to add a link_id primary key to the join table. The join table will usually consist of the primary keys of the two participating tables.

Using XML you will need syntax like this:

 <class name="Parent">
    <list name="children" table="link_table">
    <key column="parent_id"/>
    <many-to-many column="child_id"

<class name="Child">
<list name="parents" inverse="true" table="link_table">
    <key column="child_id"/>
    <many-to-many column="parent_id"

Although I find annotations better to use.