MyBatis--where 和 if 标签实现动态SQL

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 = ?
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值