Mybatis查询集合遍历出错,如何正确使用foreach判断空或null?

洼地云 tuoyidashi.png

Mybatis动态SQL的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候),可以将List、Set、数组等类型的数据作为参数。但是当List作为参数时,判断空需要特别注意。

例如:

<if test="struIds != null and struIds !='' ">
AND RELATION_ID IN
    <foreach collection="struIds" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

上面的mapper将会报错,信息如下:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.ArrayList and java.lang.String
### Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.ArrayList and java.lang.String

解决办法是:应该将判断集合是否为空的代码尽量放在程序里,如果非要让Mybatis来处理的话,可以参考下面的方式:

 <if test="struIds != null and struIds.size() > 0">
    OR RELATION_ID IN
    <foreach collection="struIds" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

 <if test="struIds != null and struIds.size > 0">
    OR RELATION_ID IN
    <foreach collection="struIds" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

References:

1.How can I skip query if where_in clause is empty in MyBatis 3?
2.mybatis 3 foreach

赞(1)
未经允许禁止转载:优米格 » Mybatis查询集合遍历出错,如何正确使用foreach判断空或null?

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册