多对多关联映射需要用第三方表来进行关联.user--->role
原理图:
对象模型如下:
public class Role {
private int id;
private String name;
}
public class User {
private int id;
private String name;
private Set roles;
}
具体映射:
Role.hbm.xml
<hibernate-mapping>
<class name="com.bjpowernode.hibernate.Role" table="t_role">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
User.hbm.xml
key在那个第三方的表中,他作为外键指向那个t_user表.
many-to-many用来告诉另外一张表hibernate现在是多对多,并且告诉hibernate这个集合里面是什么,在这里就是role,并且在这个第三方表里面加了个字段role_id 指向了这个
t_role表.第三方表的是联合主键.
测试如下:
public class Many2ManyTest extends TestCase {
public void testSave1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
Role r1 = new Role();
r1.setName("数据录入人员");
session.save(r1);
Role r2 = new Role();
r2.setName("商务主管");
session.save(r2);
Role r3 = new Role();
r3.setName("商务经理");
session.save(r3);
Role r4 = new Role();
r4.setName("项目会计");
session.save(r4);
User u1 = new User();
u1.setName("张三");
Set u1Roles = new HashSet();
u1Roles.add(r1);
u1Roles.add(r2);
u1.setRoles(u1Roles);
session.save(u1);
User u2 = new User();
u2.setName("李四");
Set u2Roles = new HashSet();
u2Roles.add(r1);
u2Roles.add(r2);
u2Roles.add(r3);
u2.setRoles(u2Roles);
session.save(u2);
User u3 = new User();
u3.setName("王五");
Set u3Roles = new HashSet();
u3Roles.add(r3);
u3Roles.add(r4);
u3.setRoles(u3Roles);
session.save(u3);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
public void testLoad1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
User user = (User)session.load(User.class, 2);
System.out.println(user.getName());
for (Iterator iter=user.getRoles().iterator(); iter.hasNext();) {
Role role = (Role)iter.next();
System.out.println(role.getName());
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
}