当前位置: 代码迷 >> 综合 >> Mybatis:foreach标签内传入list为空的解决
  详细解决方案

Mybatis:foreach标签内传入list为空的解决

热度:4   发布时间:2024-02-19 21:28:18.0

复盘一下填过的坑:

mybatis中,如果不对list就行判空处理,就会出现当list为空或者list.size=0时抛异常,错误示例如下:

 SELECT * FROM table_xxx (NOLOCK)
WHERE id in<foreach collection="list" index="index" item="item"  open="(" separator="," close=")">  #{item}</foreach>

解决方案如下:(推荐第二种)

1、对list判null和判空来处理

使用mybatis进行in()判断的时候传入参数为List,需要判断List是否为空了,当然可以在java代码中进行判断,但是我不想每次调用该方法都要进行判断,所有最好还是在mybatis的sql配置文件中判断,配置如下:

 SELECT * FROM table_xxx (NOLOCK) WHERE 
<if test="list != null and list.size() > 0">id in<foreach collection="list" index="index" item="item"  open="(" separator="," close=")">  #{item}</foreach>
</if>

2、对list判null和判空来处理(墙裂推荐)

 SELECT * FROM table_xxx (NOLOCK) 
WHERE  isActive=1
<foreach collection="list" index="index" item="item" open="AND id IN (" separator="," close=")">#{item}
</foreach>

 

  相关解决方案