How to map a many-to-many list in sleep mode with a link table

I would like to match many-to-many in Hibernate using a link table. I have two classes: "Parent and child", 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_idand child_id. The database is an SQL server, and identifier types are uniqueidentifier. Therefore, I usually use guid for id fields.

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

I am currently getting a ConstraintViolationException, but could not find any good documentation or examples of this.

, : link_id, .

+5
4

, ( ) link_id . .

XML, :

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

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

, .

+5

, @ManyToMany @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;
    }
}
+7

, . ...

-- , , XML:

0

, . , , , FK . /.

PK PK. . .

PK , ParentChildren linkId. annoated parentchildren, .

@Entity
@Table(name = "parent_children")
public class ParentChildren{
    @Id @GeneratedValue
    private long linkId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "parent_id") 
    private Parent parent;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "children_id) 
    private Children children;

    // additional fields if you want
    private boolean activated;

    //getters and setters
    }
}

, , linkId , parent_id children_id - . , , link_id .

0

All Articles