您的位置:首页 > 数据库

Mybatis中sql语句中的in查询,一定要判断null的情况

2015-05-03 00:00 501 查看
不严谨的写法,可能会报错:in (),这种情况不符合mysql的语法。
select from loanwhere LOAN_ID in
<foreach item="item" index="id" collection="list" open="(" separator="," close=")">
#{item}

要么在Mybatis的sql文件中,要么在Java程序中。

sql中的写法:
<select id="findByLoanIds" parameterType="List">
select *
from p2p_loan_variation where 1= 1
<if test="list != null and list.size>0">
and LOAN_ID in
<foreach item="item" index="id" collection="list" open="("
separator="," close=")">
#{item}
</foreach>
</if>
<if test="list==null or list.size==0">and 1=0</if>
</select>

Java中的写法:
List<LoanVariation> list = null;
if(ListUtils.isNotEmpty(loadIds){
list =loanVariationDao.findByLoanIds(loanIds);
}
return list;

如果有多个Java方法调用dao mapper,在sql中写比较省事,毕竟只需要一次“参数检查”。

上面的写法是针对一个查询条件的,如果有多个查询条件,记得处理条件之间的关系,
比如 a=1 and b =2 or c=3.
如果有in条件,最好加上括号,(a=1) and (b =2 ) or ( c in ...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis sql mysql web开发 in