場景是用戶表,角色表,權限表做權限管理;
users表 
role表 
permission表 
中間表users-role
中間表role-permission 
查詢用戶沒有的角色
在controller中
@RequestMapping("/findUserByIdAndAllRole.do") public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) int userid){ ModelAndView mv = new ModelAndView(); //查詢userid對應的對象 Users user = usersService.findById(userid); //根據userid查詢當前用戶沒有的角色信息 List<Role> otherRoles = usersService.findOtherRoles(userid); mv.addObject("user",user); mv.addObject("roleList",otherRoles); mv.setViewName("user-role-add"); return mv; }
在 dao的配置文件中mybatis配置文件
<select id="findById" resultMap="userRolePermissionMap"> select u.*,r.id as rid,r.rolename,r.roleDesc,p.permissionName,p.url from users u LEFT OUTER JOIN users_role ur on u.id = ur.userId LEFT OUTER JOIN role r on r.id = ur.roleId LEFT OUTER JOIN role_permission rp on rp.roleId = r.id LEFT OUTER JOIN permission p on p.id = rp.permissionId where u.id = #{id} </select> <select id="findOtherRoles" parameterType="int" resultType="com.hengheng.domain.Role"> select * from role where id not in (select roleid from users_role where userId = #{userid}) </select>
給用戶添加角色,前端傳過來的數據要包含當前添加用戶的 id 和 要添加的角色的id

在controller中,因為 ids 是一個數組,所以在在執行SQL時要批量操作,
@RequestMapping("/addRoleToUser.do") public String addRoleToUser(@RequestParam(name = "userId")int userid,@RequestParam(name = "ids")int[] ids){ usersService.addRoleToUser(userid,ids); return "redirect:findAll.do"; }
在dao的接口文件中要綁定參數,防止一些錯誤的發生
public interface IUsersDao { public Users findByUserName(String username); public List<Users> findAll(); public void save(Users user); public Users findById(int id); public List<Role> findOtherRoles(int userid); void addRoleToUser(@Param("map") Map<Integer, Integer> map); void addRoleToUser(@Param("userid") int userid,@Param("ids")int[] ids); }
在mapper文件中
<insert id="addRoleToUser" > insert into users_role(userId, roleId) VALUES <foreach collection="ids" index="index" item="item" separator=","> (#{userid},#{item}) </foreach> </insert>
foreach :是循環,批量操作
collection:是傳過來的集合的屬性,List默認是list,Map默認是map
index:循環的數據的索引
item:當前循環到的數據
separator:數據間的分隔符
