一.hibernate多对多映射(单项),自动产生第三张表
User--à Role
user(id,name) role(id,name)
User类:
private int id; private String name; private Set roles;
Role类:
private int id; private String name;
User.hbm.xml中:
<set name=”roles” table=”t_user_role”>
<key column=”userid” />
<many-to-many class=”com.Role” column=”roleid” />
</set>
这样,hibernate会自动产生中间表t_user_role(userid,roleid) 并且是复合主键,userid为t_user的外键,roleid为t_role的外键
二.hibernate多对多的存储
Role r1 = new Role();
r1.setName(“数据录入人员”);
Role r2 = new Role();
r2.setName(“商务主管”);
Role r3 = new Role();
r3.setName(“大区经理”);
User u1 = new User();
u1.setName(“10”);
Set u1Roles = new HashSet();
u1Roles.add(r1);
u1Roles.add(r2);
u1.setRoles(u1Roles);
User u2 = new User();
u1.setName(“祖儿”);
Set u2Roles = new HashSet();
u2Roles.add(r2);
u2Roles.add(r3);
u2.setRoles(u2Roles);
User u3 = new User();
u3.setName(“杰伦”);
Set u3Roles = new HashSet();
u3Roles.add(r1);
u3Roles.add(r2);
u3Roles.add(r3);
u3.setRoles(u3Roles);
session.save(r1);
session.save(r2);
session.save(r3);
session.save(u1);
session.save(u2);
session.save(u3);
结束之后,在第三张表中也有数据
三.hibernate多对多的加载
User user = (User)session.load(User.class,1);
System.out.println(user.getName());
for(Iterator iter = user.getRoles().iterator();iter.hasNext();){
Role role = (Role)iter.next();
System.out.println(role.getName());
}
每次加载都会发出sql语句
三.hibernate多对多的 双向映射
User ß--.-àRole
user(id,name) role(id,name)
User类:
private int id; private String name; private Set roles;
Role类:
private int id; private String name; private Set users;
User.hbm.xml中:
<set name=”roles” table=”t_user_role”>
<key column=”userid” />
<many-to-many class=”com.Role” column=”roleid” />
</set>
Role.hbm.xml中:
<set name=”roles” table=”t_user_role”> //这里可以设置order-by=”userid”,根据userid排序
<key column=”roleid” />
<many-to-many class=”com.User” column=”userid” />
</set>
注意,上面中间表名字是一样的
这样,hibernate也会自动产生中间表t_user_role(userid,roleid) 并且是复合主键,userid为t_user的外键,roleid为t_role的外键