github地址:https://github.com/VioletSY/share
(1)使用场景,现有sys_user,sys_role,sys_permission三张表,关系是1:n:n
(2)现在想通过用户的id返回用户的详细信息,包括用户拥有的角色,以及各个角色拥有的权限
/** * 获取用户的详细信息 * @param id * @return */ @Select("select a.id,a.name,b.user_id userId from sys_user a left join sys_link_user_role b on a.id = b.user_id where a.id = #{id} GROUP BY a.id,a.name ") @Results({ @Result(id = true, column = "id", property = "id") , @Result(id = true, column = "id", property = "id") , @Result(column = "username", property = "username") , @Result(column = "name", property = "name"), @Result(column = "num", property = "num") , @Result(column = "sex", property = "sex") , @Result(column = "tel", property = "tel") , @Result(column = "headimage", property = "headimage") , @Result(property="roles",many=@Many(select="selByUserId"),column="{userId=userId}")}) User get(String id); /** * 根据用户id获取用户的角色集合 * @param map * @return */ @Select("select d.id,d.code,d.name,d.num from sys_link_user_role b left join sys_role d on b.role_id = d.id where b.user_id = #{userId} ") @Results({ @Result(id = true, column = "id", property = "id") , @Result(id = true, column = "id", property = "id") , @Result(column = "code", property = "code") , @Result(property="permissions",many=@Many(select="selByRoleId"),column="{roleId=id}")}) Set<Role> selByUserId(Map<String,Object> map); /** * 根据用角色的id获取角色对应的权限集合 * @param map * @return */ @Select("select b.id,b.code,b.name,b.num from sys_link_role_permission a left join sys_permission b on a.permission_id = b.id where a.role_id = #{roleId}") Set<Permissions> selByRoleId(Map<String,Object> map);
(3)测试: