关系都是多对多的关系,双向查找。
用户类:
- import java.util.Set;
- public class RPMS_user {
- private int userId;
- private String userName;
- private String userPass;
- private Set<RPMS_role> roleId;
- //生成get/set方法
- }
映射文件:
- <hibernate-mapping package="com.softeem.dto">
- <class name="RPMS_user" >
- <id name="userId">
- <generator class="native"/>
- </id>
- <property name="userName" />
- <property name="userPass"></property>
- <set name="roleId" table="RPMS_user_role" lazy="false" cascade="all">
- <key column="userid"></key>
- <many-to-many class="com.softeem.dto.RPMS_role" column="roleid"></many-to-many>
- </set>
- </class>
- </hibernate-mapping>
下面的只说类,映射文件都差不多,理解下都可以写出来
角色类:
- public class RPMS_role {
- private int roleId;
- private String roleName;
- private RPMS_owner ownerId;
- private Set<RPMS_power> powerId;
- private Set<RPMS_user> userId;
- //生成get/set方法
- }
权限类:
- public class RPMS_power {
- private int powerId;
- private String powerName;
- private Set<RPMS_role> roles; //保存的多个角色
- }
添加一个对象,在这里就不多说了,在这里最要是说下怎样来形成关系,和一些可能出现的错误:
添加形成关系:
- public String AddUserRole(){
- //查找角色
- role=uservice.selectRoleById(role);
- Set<RPMS_role> set = new HashSet<RPMS_role>();
- set.add(role);
- //把角色添加到用户中
- user.setRoleId(set);
- uservice.addUser(user);
- return SUCCESS;
- }
关键是说下,怎么从一个多对多的实例中添加或删除一条记录而不影响其他记录:
添加:
- /**
- * 用于为角色添加对应的权限
- * 先获取到选择的权限 以及角色
- * 然后把权限保存到角色中去
- **/
- public String AddRolePower(){
- if(chickid!=null&&chickid.size()>0){
- for(int i=0;i<chickid.size();i++){
- System.out.println(chickid.get(i));
- RPMS_power pw = new RPMS_power();
- pw.setPowerId(chickid.get(i));
- power=uservice.selectPowerById(pw);
- plist.add(power);
- }
- role=uservice.selectRoleById(role);
- Set<RPMS_power> set = new HashSet<RPMS_power>();
- for(int i=0;i<plist.size();i++){
- set.add(plist.get(i));
- }
- role.setPowerId(set);
- uservice.AddRolePower(role);
- }
- return SUCCESS;
- }
删除:
- /**删除权限功能
- * 先获取用户提交的权限
- * 然后获取角色中有的权限
- * 判断用户提交的权限在角色中是否存在
- * 最后再对存在的权限进行删除功能
- * **/
- public String DelRolePower(){
- if(chickid!=null&&chickid.size()>0){
- role=uservice.selectRoleById(role);
- for(int i=0;i<chickid.size();i++){
- Iterator<RPMS_power> it =role.getPowerId().iterator();
- while(it.hasNext()){
- RPMS_power wer=it.next();
- if(chickid.get(i)==wer.getPowerId()){
- plist.add(wer);
- }
- }
- }
- for(int i=0;i<plist.size();i++){
- role.getPowerId().remove(plist.get(i));
- }
- uservice.AddRolePower(role);
- }
- return SUCCESS;
- }