hibernate实例简析-hibernate_many2many_2

hibernate多对多关联映射(双向User<---->Role)

映射方法:
<set name="roles" table="t_user_role">
<key column="userid"/>
<many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/>
</set>
table属性值必须和单向关联中的table属性值一致
<key>中column属性值要与单向关联中的<many-to-many>标签中的column属性值一致
在<many-to-many>中的column属性值要与单向关联中<key>标签的column属性值一致
===
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);

User u1 = new User();
u1.setName("10");
Set u1Roles = new HashSet();
u1Roles.add(r1);
u1Roles.add(r2);
u1.setRoles(u1Roles);

User u2 = new User();
u2.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(u1);
session.save(u2);
session.save(u3);
---
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());
}
---
Role role = (Role)session.load(Role.class, 1);
System.out.println(role.getName());
for (Iterator iter=role.getUsers().iterator(); iter.hasNext();) {
User user = (User)iter.next();
System.out.println(user.getName());
}
===
<hibernate-mapping>
<class name="com.bjsxt.hibernate.Role" table="t_role">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="users" table="t_user_role" order-by="userid">
<key column="roleid"/>
<many-to-many class="com.bjsxt.hibernate.User" column="userid"/>
</set>
</class>
</hibernate-mapping>
===
<hibernate-mapping>
<class name="com.bjsxt.hibernate.User" table="t_user">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="roles" table="t_user_role">
<key column="userid"/>
<many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/>
</set>
</class>
</hibernate-mapping>
===
public class User {

private int id;

private String name;

private Set roles;
===
public class Role {

private int id;

private String name;

private Set users;
===
==
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值