ORM框架Hibernate (五) 多对多关联映射
package com.bjpowernode.hibernate;import java.util.Set;/** * 用户实体类 * @author LLS * */public class User {//具有的属性private int id;private String name;//保存多的一方的实体信息private Set roles;//getter和setter方法public Set getRoles() {return roles;}public void setRoles(Set roles) {this.roles = 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;}}
package com.bjpowernode.hibernate;/** * 角色实体类 * @author LLS * */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;}}
<?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"></generator></id> <property name="name"></property><!-- 由于这种多对多是单方向的,关系表的维护在用户一端完成。<key>属性默认会把User表的主键加入关系表中,作为一列<many-to-many>会关关联表的主键也加入到关联表中理解了一对多映射,多对多会觉得很简单 --> <set name="roles" table="t_user_role"><key column="user_id"></key><many-to-many class="com.bjpowernode.hibernate.Role" column="role_id"/></set></class></hibernate-mapping>
<?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"></generator></id><property name="name"></property><set name="users" table="t_user_role"><key column="role_id"></key><many-to-many class="com.bjpowernode.hibernate.User" column="user_id"></many-to-many></set></class> </hibernate-mapping>
<?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"></generator></id><property name="name"></property><set name="users" table="t_user_role"><key column="role_id"></key><many-to-many class="com.bjpowernode.hibernate.User" column="user_id"></many-to-many></set></class> </hibernate-mapping>