欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多对多关联映射(双向关联)见项目:me_many_to_many

程序员文章站 2022-05-21 13:51:06
...

1.模型
一个用户拥有多个角色,一个角色拥有多个用户。
2.实体类(省略set,get方法)

public class User {
private int id;
private String name;
private Set roles;
}

 

public class Role {
private int id;
private String name;
private Set users;
}

 
3.数据模型
mysql> desc t_user;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
mysql> desc t_role;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
4.映射文件
User.hbm.xml

<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>

 

Role.hbm.xml

<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">
<key column="roleid"/>
<many-to-many class="com.bjsxt.hibernate.User" column="userid"/>
</set>
</class>
</hibernate-mapping>

 

<key>中的column属性值必须等于单向关联中<many-to-many>标签指向的column的属性值
<many-to-many>中column属性值必须等于单向关联中<key>中column的属性值
5.测试

public class ManyToManyTest extends TestCase {
//存储
public void testSave(){
Session session = HibernateUtils.getSession();
Transaction tx = session.beginTransaction();
User user1 = new User();
user1.setName("yang9");
session.save(user1);
User user2 = new User();
user2.setName("long1");
session.save(user2);
Set<User> users = new HashSet<User>();
users.add(user1);
users.add(user2);
Role role1 = new Role();
role1.setName("凤山人在线");
role1.setUsers(users);
session.save(role1);
tx.commit();
}
//导入
public void testLoad(){
Session session =HibernateUtils.getSession();
Transaction tx = session.beginTransaction();
Role role = (Role) session.load(Role.class, 1);
System.out.println(role.getName());
for(Iterator ite=role.getUsers().iterator();ite.hasNext();){
User user = (User) ite.next();
System.out.println(user.getName());
}
}