Mybatis中sql语句中的in查询,判断null和size为0的情况
不严谨的写法,可能会报错:in (),这种情况不符合SQL的语法,导致程序报错。
如果简单只做非空判断,这样也有可能会有问题:本来in一个空列表,应该是没有数据才对,却变成了获取全部数据。
所以一个比较周全的方法是:
<select id="getPage" resultMap="BaseResultMap" parameterType="Map">
SELECT * FROM
t_user_car
<where>
delete_flag = 0
<if test="userIdList != null and userIdList.size>0">
AND user_id in
<foreach collection="userIdList" index="" item="item"
separator="," open="(" close=")">
#{item}
</foreach>
</if>
<if test="userIdList == null or userIdList.size == 0">and 1=0</if>
<if test="keywords!=null and keywords!='' ">
AND (car_number LIKE CONCAT('%', #{keywords}, '%'))
</if>
</where>
ORDER BY create_time ASC
</select>
如上,加2个if判断,如果为空则永远让语句查询不到数据