Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 link_id, parent_id, and child_id. 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 link_id to be automatically generated in the link table.

like image 522
Brandon Avatar asked Dec 22 '08 23:12

Brandon


People also ask

How do you map a many-to-many?

In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations. Let's have a closer look at them. The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.

How do you map an entity to multiple tables in hibernate?

Yes, you can map an entity to 2 database tables in 2 simple steps: You need to annotate your entity with JPA's @Table and @SecondaryTable annotations and provide the names of the first and second table as the value of the name parameters.

How many tables are created in many-to-many relationship hibernate?

Hibernate creates two tables in a many to many relationship.

Which of the following element is used to map many-to-many relationship in hibernate?

Define Hibernate Mapping File The <set> element will be used to define the rule for manyto-many relationship. The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.


1 Answers

I do this using annotations, specifically @ManyToMany and @JoinTable:

Hibernate Docs:

@Entity
public class Employer implements Serializable {
    @ManyToMany(
        targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,
        cascade={CascadeType.PERSIST, CascadeType.MERGE}
    )
    @JoinTable(
        name="EMPLOYER_EMPLOYEE",
        joinColumns=@JoinColumn(name="EMPER_ID"),
        inverseJoinColumns=@JoinColumn(name="EMPEE_ID")
    )
    public Collection getEmployees() {
        return employees;
    }
}


@Entity
public class Employee implements Serializable {
    @ManyToMany(
        cascade = {CascadeType.PERSIST, CascadeType.MERGE},
        mappedBy = "employees",
        targetEntity = Employer.class
    )
    public Collection getEmployers() {
        return employers;
    }
}
like image 167
Matt Lewis Avatar answered Sep 25 '22 06:09

Matt Lewis