hibernate多对多

hibernate多对多处理设置

例如角色与权限:

角色中:

privateSetprivileges=newHashSet();

权限中:

privateSet<Role>roles=newHashSet<Role>();

<classname="entity.Role"table="ROLE"dynamic-update="true">

<idname="roleId"type="java.lang.Integer">

<columnname="roleID"/>

<generatorclass="identity"></generator>

</id>

<propertyname="roleName"type="java.lang.String">

<columnname="roleName"length="50"/>

</property>

<propertyname="mender"type="java.lang.Integer">

<columnname="mender"/>

</property>

<propertyname="modifyTime"type="java.sql.Timestamp">

<columnname="modifyTime"length="50"/>

</property>

<setname="privileges"cascade="all"table="ROLE_PRIVILEGE"lazy="true">

<keycolumn="roleID"/>

<many-to-manyclass="entity.Privilege"column="pvID"order-by="sequence"/>

</set>

</class>

<classname="entity.Privilege"table="PRIVILEGE">

<idname="pvId"type="java.lang.Integer">

<columnname="pvID"/>

<generatorclass="identity"></generator>

</id>

<propertyname="parentId"type="java.lang.Integer">

<columnname="parentID"/>

</property>

<propertyname="pvName"type="java.lang.String">

<columnname="pvName"length="50"/>

</property>

<propertyname="level"type="java.lang.Short">

<columnname="level"/>

</property>

<propertyname="url"type="java.lang.String">

<columnname="url"length="50"/>

</property>

<propertyname="isView"type="java.lang.Short">

<columnname="isView"/>

</property>

<propertyname="modifyTime"type="java.sql.Timestamp">

<columnname="modifyTime"length="50"/>

</property>

<setname="roles"table="ROLE_PRIVILEGE"lazy="true"cascade="none">

<keycolumn="pvID"/>

<many-to-manyclass="entity.Role"column="roleID"/>

</set>

</class>

修改角色的时候1根据id去查询角色实体

2将需要更新的字段更新到查询出来的角色实体中

修改角色的权限1删除当前角色的权限

2添加当前角色权限

实例:

publicvoidupdatePvRole(Integer[]pvIds,IntegerroleId){

if(pvIds==null||pvIds.length==0){

return;

}

Rolerole=roleDao.getRole(roleId);

SetsetOld=role.getPrivileges();

Iteratorit=setOld.iterator();

while(it.hasNext()){

it.next();

it.remove();

}

for(IntegerpvId:pvIds){

Privilegeprivilege=privilegeDao.getPrivilege(pvId);

setOld.add(privilege);

}

roleDao.updateRole(role);

}

相关推荐