不严谨的写法,可能会报错: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中的写法:

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

上面的写法是针对一个查询条件的,如果有多个查询条件,记得处理条件之间的关系,

比如 a=1 and b =2 or c=3.

如果有in条件,最好加上括号,(a=1) and (b =2 ) or ( c in ...)