MyBatis单个参数的动态语句引用

在使用mybatis的动态sql时,有时需要根据参数值来动态拼接mysql,比如下面的示例:
根据出版社和作者查询图书列表,如果为空则不做该条件过滤(注:此处有2个参数)

public void getBookList(String publisher,String author){
         Map<String,Object> maps = new HashMap<String, Object>();
         maps.put("publisher", publisher);
         maps.put("author", author);
         
         this.getListByEntity("getBookList",maps);
}

<select id="getBookList"  resultType="Book">
         SELECT * FROM bookinfo
         <where>
                   <if test="publisher != null">
                            publisher = #{publisher}
                   </if>
                   <if test="author != null">
                            AND author = #{author}
                   </if>
         </where>
</select>

如上写法,是没有问题的,但是当情况变得简单的时候,比如只根据作者查询图书列表的时候,当然我们可以采用和上面相同的处理方法,在方法中将参数封装到map中去。但是当我们直接使用String作为参数来查询时,就需要注意一个问题:

public void getBookList(String author){

         this.getListByEntity("getBookListByAuthor",author);
}

<select id="getBookListByAuthor" parameterType="java.lang.String" resultType="Book">
         SELECT * FROM bookinfo
         <where>
                   <if test="author != null">
                            author = #{author}
                   </if>
         </where>
</select>

看似没有问题,当我们运行的时候,报异常了,原因是当我们的参数为String时,在sql语句中#{author} 会去我们传进来的参数调getAuthor()方法获取参数,很明显,String没有对应的方法,所以报错了,那我们这里要如何引用author对象呢,需要采用下面的写法:

<select id="getBookListByAuthor" parameterType="java.lang.String" resultType="Book">
         SELECT * FROM bookinfo
         <where>
                   <if test="_parameter != null">
                            AND author = #{author}
                   </if>
         </where>
</select>

结论当mybatis传参为单个参数时,在sql语句中需要使用_parameter 来引用这个参数

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值