create table contact (
last_name varchar(50),
first_name varchar(50),
primary key (contact_id)) engine=innodb ;
create table my_user (
user_id int(11) not null auto_increment ,
last_name varchar(50),
first_name varchar(50),
primary key (user_id)) engine=innodb ;
create table my_group (
group_id int(11) not null auto_increment ,
name varchar(50),
primary key (group_id)) engine=innodb ;
create table user_group(
user_group_id int(11) not null auto_increment ,
group_id int(11) not null ,
user_id int(11) not null ,
primary key (user_group_id)) engine=innodb ;
user group is the link table. Now we want to see the mapping files for user and group classes. There is no need for a separate mapping file in case of mysql if you are using the auto_increment primary keys. But when I map to oracle , i usually keep a mapping file for link table also. Just map the link table primary key column. The mappings for groups follow in User.hbm.xml. This is the inverse end of relationship. I have omitted other property mappings for brevity sake.
<key column="user_id"/>
<many-to-many class="com.agiti.hib.Group" column="group_id" />
</set>
<collection-id column="user_group_ID" type="java.lang.Long">
<generator class="increment"/>
</collection-id>
<key column="group_id"/>
<many-to-many column="user_id" class="com.agiti.hib.User"/>
After you are through with the mappings, create or reverse engineer the POJO classes. inside Group.java, the relevant bits are :
private Long id ;
private String name ;
private List users = new ArrayList();
public List getUsers(){ return this.users ;}
public void setUsers(List users){ this.users = users ;}
// other details nuked
public void addUser(User user){
this.users.add(user);
user.getGroups().add(this);
}
}
You can write User.java on the same lines. After that it is just a matter of using your POJO classes.