Alan's Blog

导航

使用hibernate建立多对多关系

使用Hibernate的映射可以建立两个类(表)之间的关系。如想POJO可以建立角色和功能点的关系,他们是多对多的关系,可通过映射和POJO类来建立关系,使用如下方法并不需要建立第三张表,在FunctionPoint.java添加    private Set<Role> roles = new HashSet<Role>();,Role.java添加private Set<FunctionPoint> functionPoints = new HashSet<FunctionPoint>();即可

Role.hbm.xml

代码
1 <class name="Role" table="t_sys_role" dynamic-insert="true" dynamic-update="true">
2 <id name="id" type="string">
3 <column name="f_id" sql-type="nvarchar2(32)"/>
4 <generator class="uuid.hex" />
5 </id>
6 <set name="functionPoints" table="t_sys_role_function_point" lazy="true" inverse="false" cascade="all">
7 <key>
8 <column name="f_role_id" sql-type="nvarchar2(32)"/>
9 </key>
10 <many-to-many class="com.zyeeda.projs.cmsz.pojos.FunctionPoint" >
11 <column name="f_function_point_id" sql-type="nvarchar2(32)" />
12 </many-to-many>
13 </set>

FunctionPoint.hbm.xml

 

代码
<class name="FunctionPoint" table="t_sys_function_point" dynamic-insert="true" dynamic-update="true">
<id name="id" type="string">
<column name="f_id" sql-type="nvarchar2(32)"/>
<generator class="uuid.hex" />
</id>
<set name="roles" table="t_sys_role_function_point" lazy="true" inverse="true" cascade="all">
<key>
<column name="f_function_point_id" sql-type="nvarchar2(32)"/>
</key>
<many-to-many class="com.zyeeda.projs.cmsz.pojos.Role" >
<column name="f_role_id" sql-type="nvarchar2(32)" />
</many-to-many>
</set>

Role.java(POJO)

 

 

代码
public class Role{

private Set<FunctionPoint> functionPoints = new HashSet<FunctionPoint>();

public void setFunctionPoints(Set<FunctionPoint> functionPoints) {
this.functionPoints = functionPoints;
}
public Set<FunctionPoint> getFunctionPoints() {
return this.functionPoints;
}
}

FunctionPoint.hbm.xml

 

 

代码
public class FunctionPoint extends Entity {

private Set<Role> roles = new HashSet<Role>();

public Set<Role> getRoles(){
return roles;
}

public void setRoles(Set<Role> roles){
this.roles = roles;
}

}

使用如下语句可以建立他们之间的关系:实现一个角色拥有多种功能权限

 

 

代码
String id = cmd.getParameter("id");
String[] functionArray
= cmd.getParameterValues("childArray");
List functionPoints
= this.getFunctionPointManager().getFunctionPointByfunctionPointIds(session, functionArray);
Role role
= (Role)this.getFunctionPointManager().getRoleByRoleId(session, id).get(0);

// 解除两者之间的关联关系
role.getFunctionPoints().clear();
for(int i=0;i<functionPoints.size();i++){
FunctionPoint functionPoint
= (FunctionPoint)functionPoints.get(i);
functionPoint.getRoles().clear();
}
//建立两者之间的关联关系
for(int i=0;i<functionPoints.size();i++){
FunctionPoint fPoint
= (FunctionPoint)functionPoints.get(i);
role.getFunctionPoints().add(fPoint);
fPoint.getRoles().add(role);
}

本来也可以使用第三张表建立角色和功能之间多对多的关系,但完全没有必要,可以使用上面我写的配置来映射出第三张表(启动服务器时就能够在数据库建立起来)

 

posted on 2010-07-29 21:10  Alan's Blog  阅读(1832)  评论(0编辑  收藏  举报