MyBatis–where 和 if 标签实现动态SQL
项目中经常需要多条件查询,我们自己去拼and或者or连接符比较麻烦,我们可以用where和if标签来实现。
controller:
@GetMapping("/")
public Result getUserById(HttpServletRequest request){
Result result = new Result();
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
String email = request.getParameter("email");
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("id",id);
paramMap.put("name",name);
paramMap.put("age",age);
paramMap.put("email",email);
result.setCode(200);
result.setData(userService.getUserById(paramMap));
return result;
}
dao接口:
List<User> getUserById(@Param("param")Map<String,Object> paramMap);
xml文件:
<select id="getUserById" parameterType="Integer" resultType="entity.User">
select * from user2
<where>
<if test="param.id!=null and param.id!=''">
and id=${param.id}
</if>
<if test="param.name!=null and param.name!=''">
and name like '%${param.name}%'
</if>
<if test="param.age!=null and param.age!=''">
and age = ${param.age}
</if>
<if test="param.email!=null and param.email!=''">
and email like '${param.email}'
</if>
</where>
</select>
postman进行测试:
说明:
<where>是用来拼接where条件的,当下面的判断全为false时就不会往sql中加‘where’。
如果我们一个条件都不穿,最后的sql是:
select * from user2
<if>标签是用来判断是否添加下面的条件。
如
<if test="param.id!=null and param.id!=''">
and id=${param.id}
</if>
test的结果为true时,在sql后面添加and id=${param.id},
为false时则不添加。
另外,如果我们只有一个条件成立时,where标签会自动帮我们去掉第一个and或者or连接符。比如当我们传了id时,最后的sql是
select * from user2 where id = ?