Hibernate中的关系映射,最常见的关系映射之一就是多对多关系映射例如用户与角色的关系,一个用户对应多个角色,一个角色对应多个用户。如图:
下面就为大家讲解一下:Hibernate中如何来映射这两个的关系呢?
1、创建实体类User和实体类Role
User.java
package com.bjpowernode.hibernate; import java.util.Set; public class User { private int id; private String name; private Set roles; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } }
Role.java
package com.bjpowernode.hibernate; public class Role { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }2、创建映射文件User.hbm.xml和Role.hbm.xml
User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bjpowernode.hibernate.User" table="t_user"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="roles" table="t_user_role"> <key column="user_id"/> <many-to-many class="com.bjpowernode.hibernate.Role" column="role_id" /> </set> </class> </hibernate-mapping>
Role.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bjpowernode.hibernate.Role" table="t_role"> <id name="id"> <generator class="native"/> </id> <property name="name"/> </class> </hibernate-mapping>
3、效果图