med
med

Reputation: 1600

Multiple foreign key mapping

I am trying to learn Hibernate and i can't solve a design problem. I have Head and Group Classes. I have generated two tables listed below using hibernate.

Table-Head
id, int4, primary key
name, varchar 50
description, varchar 250

Table-Group 
id, int4, primary key
name, varchar 25
description, varchar 250

I just want to ask how can i generate HeadAndGroup table which is listed below? I have tried to write HeadAndGroup as separate class but i can't handle it.

Table HeadAndGroup (Many to Many)
id , int4, primary key
head_id , int4, foreign key -> head table
group_id , int4, foreign key -> group table


**head_id, group_id pair will be unique

Upvotes: 0

Views: 1796

Answers (1)

Pulkit Goyal
Pulkit Goyal

Reputation: 5654

You can add a Collection<Head> heads in your Group class with @ManyToMany annotation. Hibernate will then handle the HeadAndGroup table for you.

@ManyToMany(
    targetEntity=Head.class,
    cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
public Collection getHeads() {
    return heads;
}

Have a look here for details.

Upvotes: 1

Related Questions