Mybatis中sql语句中的in查询,判断null和size为0的情况

不严谨的写法,可能会报错:in (),这种情况不符合SQL的语法,导致程序报错。

如果简单只做非空判断,这样也有可能会有问题:本来in一个空列表,应该是没有数据才对,却变成了获取全部数据!

所以一个比较周全的方法是:

    <select id="findLastPoolTaskIdsForMo" resultMap="poolTaskResult">
        SELECT  MIN(p.pool_task_id) AS pool_task_id
        FROM    pool_task p
        WHERE r_type != 2
        <if test="moCodeList != null and moCodeList.size>0">
            AND p.mo_code IN
            <foreach collection="moCodeList" item="item" index="index" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <if test="moCodeList==null or moCodeList.size==0">and 1=0</if>
        GROUP BY p.mo_code
    </select>

如上,加2个if判断,如果为空则永远让语句查询不到数据  

原文地址:https://www.cnblogs.com/xujanus/p/7611401.html