1. 给子查询传递一个值
@Select({“select * from user where username = #{userName}”}) ①
@Results({
@Result(
property = “id”, column = “id” ②
),
@Result(
property = “roleList”,column=“id”, ③
many = @Many(select = “com.x.dt.mapper.UserMapper.selectByUserNameRoleId”)
)})
List selectByName(String userName);
@Select({"select id from role where id in(select role_id from user_role where user_id=#{userId})"})
List<Role> selectByUserNameRoleId(@Param("userId") String userId);
三个表
用户表: user
角色表:role
用户角色关联表:user_role
- ①主查询,查询得到结果;
- 将主查询结果里面的id字段赋给③;
- ③里面的id为子查询的条件,③的id与①主查询里面的数据库字段相对应;
- selectByUserNameRoleId通过③的coulmn为查询条件。
2. 给子查询传递多个值
@Mapper---------------主查询和子查询都要打上注解Mapper,才可以映射过去
@Select("<script>"
+ "SELECT user_id "
+ "CASE "
+ "WHEN (#{userName} = '' or #{userName} is null) "
+ "THEN NULL "
+ "ELSE #{userName} END AS user_name"---------------------核心语句,注意这边是=不是==
+ "FROM sys_user "
+ "</script>")
@Results({
@Result(column = "{userName=user_name,userId=user_id}", property = "userList", javaType = List.class,
many = @Many(select = "com.dao.xxxDao.searchXxxByName"))--------------------------property是查询返回映射到DTO里面的变量,在column里面放置传到查多语句中的参数userName,userId
})
List<XxxDto> searchXxx(@Param("userName") String userName);---------传递过去的参数
@Mapper
@Select("<script>"
+ "SELECT * "
+ "FROM sys_detail "
+ "<if test=\"userId!=null \"> "
+ "AND user_id =#{userId} "
+ "</if> "
+ "<if test=\"userName!=null and userName!=\'\' \"> "
+ "AND user_name=#{userName} "
+ "</if> "
+ "</script>")
List<SysDetail> searchXxxByName(Map<String, String> param);------对应的参数一定要是Mapper