目录
二、在xml文件中使用foreach来遍历parameterType的list
一、前景提要
有一个需求是:
根据当前账号的权限设置登录后显示的一二级分类,也就是管理员可以看到所有的界面,而权限低一点的可能就看到的少一点。
第一种做法:(也是浪费我阳间时间的做法,太**了)
根据userid查询当前用户的所有能访问的一级和二级菜单的list集合然后再在controller类中进行封装?
答案是:NO!
正确做法如下:()
**
* @author Dragon code!
* @create 2022-04-13 9:59
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Reference(check = false)
private UserService userService;
@RequestMapping("/getusername")
public Result getUsername(){
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
User user = userService.findUserByUserName(username);
if (user == null) {
return null;
}
HashMap<String, Object> map = new HashMap<>();
map.put("username",username);
HashMap<String, Object> results = new HashMap<String, Object>();
List<Menu> result = userService.findMenuByUserId(user.getId());
map.put("menuList",result);
return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, map);
} catch (Exception e) {
return new Result(false, MessageConstant.GET_USERNAME_FAIL);
}
}
}
xml文件:
首先通过userid来查询所有的一级分类,精髓在于此处的resultMap是自己自定义的map
<select id="findMenuByUserId" resultMap="findByIdRM">
SELECT
c.*
FROM
t_role a,
t_role_menu b,
t_menu c
WHERE
a.id IN ( SELECT role_id FROM t_user_role WHERE user_id = #{value} )
AND a.id = b.role_id and b.menu_id = c.id and c.`level` =1
ORDER BY
c.priority ASC
</select>
定义baseMap:
通常是某个pojo的实体类映射的map
<resultMap id="baseRM" type="menuPro">
<!-- 主键 property为实体类属性 column为数据库字段 jdbcType为实体类对应的jdbc类型-->
<id property="id" column="id"/>
<!-- 普通属性 property为实体类属性 column为数据库字段 jdbcType为实体类对应的jdbc类型-->
<result property="title" column="name"/>
<result property="linkUrl" column="linkUrl"/>
<result property="path" column="helpCode"/>
<result property="priority" column="priority"/>
<result property="description" column="description"/>
<result property="icon" column="icon"/>
<result property="parentMenuId" column="parentMenuId"/>
</resultMap>
第二步,用自己最后想返回的map来继承这个基础map
在原有单个menu的基础上向其中加入子列表的list
<resultMap id="findByIdRM" type="menuPro" extends="baseRM">
<!--其中ofType是单个对象的类型-->
<collection property="children"
ofType="menuPro"
javaType="ArrayList"
column="id"
select="com.lay.kangan.mapper.UserMapper.findChileIdByParentId"/>
</resultMap>
子列表的结果由他的子查询来完成,注意此子查询可以直接放在本xml文件中,也可以用全限定接口名来引用其他xml文件中的方法。
通过父分类的id来查询子分类:
查询的结果会直接封装到list中。
<select id="findChileIdByParentId" resultType="menuPro">
select a.*,a.name title from t_menu a where parentMenuId = #{value} order By priority ASC
</select>
至此查询返回的一级分类中就有二级分类了!
二、在xml文件中使用foreach来遍历parameterType的list
比如传入的是List<Integer> 类型的list
使用方法如下:
SELECT * FROM t_checkitem
WHERE id IN
<foreach item = "id" index = "index" collection = "list" open = "(" close = ")" separator = "," >
#{id}
</foreach>