用户关联角色操作
从前台发送请求
<a href="${pageContext.request.contextPath}/user/findUserByIdAndAllRole.do?id=${user.id}" class="btn bg-olive btn-xs">添加角色</a>
查询用户以及用户可以添加的角色
usercontroller
//查询用户以及用户可以添加的角色 @RequestMapping("/findUserByIdAndAllRole.do") public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userid) throws Exception { ModelAndView mv = new ModelAndView(); //1.根据用户id查询用户 UserInfo userInfo = userService.findById(userid); //2.根据用户id查询可以添加的角色 List<Role> otherRoles = userService.findOtherRoles(userid); mv.addObject("user", userInfo); mv.addObject("roleList", otherRoles); mv.setViewName("user-role-add"); return mv; }
UserServiceImpl
@Override public UserInfo findById(String id) throws Exception { return userDao.findById(id); } @Override public List<Role> findOtherRoles(String userid) throws Exception { return userDao.findOtherRoles(userid); }
IUserDao
@Select("select * from users where id=#{id}") @Results({ @Result(id = true, property = "id", column = "id"), @Result(property = "username", column = "username"), @Result(property = "email", column = "email"), @Result(property = "password", column = "password"), @Result(property = "phoneNum", column = "phoneNum"), @Result(property = "status", column = "status"), @Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select = "com.itheima.ssm.dao.IRoleDao.findRoleByUserId")) }) UserInfo findById(String id) throws Exception; @Select("select * from role where id not in (select roleId from users_role where userId=#{userId})") List<Role> findOtherRoles(String userId) throws Exception; //@Param 有两个int参数mybaties不知道怎末匹配 @Insert("insert into users_role(userId,roleId) values(#{userId},#{roleId})")
给用户添加角色
usercontroller
//给用户添加角色 @RequestMapping("/addRoleToUser.do") public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception{ userService.addRoleToUser(userId, roleIds); return "redirect:findAll.do"; }
UserServiceImpl
@Override public void addRoleToUser(String userId, String[] roleIds) throws Exception { for(String roleId:roleIds){ userDao.addRoleToUser(userId,roleId); } }
IUserDao
//@Param 有两个int参数mybaties不知道怎末匹配 @Insert("insert into users_role(userId,roleId) values(#{userId},#{roleId})") void addRoleToUser(@Param("userId") String userId,@Param("roleId") String roleId) throws Exception; }