0

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
med
  • 1,540
  • 1
  • 15
  • 27

1 Answers1

1

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.

Pulkit Goyal
  • 5,604
  • 1
  • 32
  • 50
  • Yes it creates table with head_id and group_id pairs. but i need one more id (primary key) attribure. How can handle this? Btw, is head_id and group_id pair unique? – med Feb 07 '12 at 12:40
  • You cannot add other columns to the hibernate generated table. To add another column, have a look at http://stackoverflow.com/a/1168740/643109 – Pulkit Goyal Feb 07 '12 at 15:30