SQL(MY SQL):
create table tgroup (
group_id int not null auto_increment,
name varchar(16) not null default '',
primary key (group_id)
) type=innodb;
create table trole (
role_id int not null auto_increment,
name varchar(16) not null default '',
primary key (role_id)
) type=innodb;
create table tgroup_role (
group_id int not null,
role_id int not null,
primary key(group_id, role_id),
index (group_id),
foreign key (group_id) references tgroup(group_id),
index (role_id),
foreign key (role_id) references trole(role_id)
) type=innodb;
Group 类:
package ivan.hibernate.many2many;
public class Group {
private int id;
private String name;
private Set roles = new HashSet();
...
}
Group.hbm.xml:
<hibernate-mapping>
<class name="ivan.hibernate.many2many.Group" table="tgroup">
<id name="id" column="group_id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" type="string"/>
<set name="roles"
table="tgroup_role"
cascade="save-update">
<key column="group_id"/>
<many-to-many class="ivan.hibernate.many2many.Role"
column="role_id"/>
</set>
</class>
</hibernate-mapping>
Role 类:
package ivan.hibernate.many2many;
public class Role {
private int id;
private String name;
private Set groups = new HashSet();
...
}
Role.hbm.xml:
<hibernate-mapping>
<class name="ivan.hibernate.many2many.Role" table="trole">
<id name="id" column="role_id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" type="string"/>
<set name="groups"
table="tgroup_role"
inverse="true"
cascade="save-update">
<key column="role_id"/>
<many-to-many class="ivan.hibernate.many2many.Group"
column="group_id"/>
</set>
</class>
</hibernate-mapping>
hibernate.cfg.xml 同前面的例子差不多。
public class Test {
public static void main(String[] args) throws HibernateException {
Role role1 = new Role();
role1.setName("Role1");
Role role2 = new Role();
role2.setName("Role2");
Role role3 = new Role();
role3.setName("Role3");
Group group1 = new Group();
group1.setName("group1");
Group group2 = new Group();
group2.setName("group2");
Group group3 = new Group();
group3.setName("group3");
group1.getRoles().add(role1);
group1.getRoles().add(role2);
group2.getRoles().add(role2);
group2.getRoles().add(role3);
group3.getRoles().add(role1);
group3.getRoles().add(role3);
role1.getGroups().add(group1);
role1.getGroups().add(group3);
role2.getGroups().add(group1);
role2.getGroups().add(group2);
role3.getGroups().add(group2);
role3.getGroups().add(group3);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx= session.beginTransaction();
session.save(role1);
session.save(role2);
session.save(role3);
session.save(group1);
session.save(group2);
session.save(group3);
tx.commit();
session.close();
sessionFactory.close();
}
}