标签:bsp inter for 添加用户 foreach 查询 eid sele rss
场景是用户表,角色表,权限表做权限管理;
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:数据间的分隔符
标签:bsp inter for 添加用户 foreach 查询 eid sele rss
原文地址:https://www.cnblogs.com/bozhengheng/p/12790361.html