Hibernate使用——多对多关联示例
TRole.java
package learnHibernate.bean;import java.io.Serializable;import java.util.HashSet;import java.util.Set;public class TRole implements Serializable{private static final long serialVersionUID = -2404169291623739243L;private int id;private String name;private Set<TPrivilege> privileges = new HashSet<TPrivilege>();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<TPrivilege> getPrivileges() {return privileges;}public void setPrivileges(Set<TPrivilege> privileges) {this.privileges = privileges;}}
?TRole.hbm.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="learnHibernate.bean"><class name="TRole" table="t_role"><id name="id" column="id" type="java.lang.Integer"><generator column="name" type="java.lang.String"/><set name="privileges" table="t_role_privilege" lazy="false" cascade="save-update"> <key column="rid"/> <many-to-many column="pid"/></set></class></hibernate-mapping>
?
TPrivilege.java
package learnHibernate.bean;import java.io.Serializable;import java.util.HashSet;import java.util.Set;public class TPrivilege implements Serializable{private static final long serialVersionUID = -5315523735464709855L;private int id;private String name;private Set<TRole> roles = new HashSet<TRole>(); 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<TRole> getRoles() {return roles;}public void setRoles(Set<TRole> roles) {this.roles = roles;}}
?TPrivilege.hbm.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="learnHibernate.bean"><class name="TPrivilege" table="t_privilege"><id name="id" column="id" type="java.lang.Integer"><generator column="name" type="java.lang.String"/><set name="roles" table="t_role_privilege" lazy="false" inverse="true" cascade="save-update"> <key column="pid"/> <many-to-many column="rid"/></set></class></hibernate-mapping>
?
注意映射文件中,cascade设置为“save-update”,是因为对于多对多的逻辑而言,很少出现删除一方需要级联删除所有关联数据的情况,如删除一个“团长”角色,不会删除其包含的所有权限,同样,删除一个权限,不会删除与之关联的所有角色。
多对多的两方不能都是主控方,也就是说,要在其中的一个映射配置中设置inverse为true。没有主控方也不行,因为那样hibernate不会插中间表。
?