欢迎光临
我们一直在努力

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

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) 打赏
未经允许不得转载:Ddmit » Mybatis查询集合遍历出错,如何正确使用foreach判断空或null?

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册