[Mybatis]-foreach遍历List与数组的情况
遍历
1.出现的情况, 如果list为空或者size为0,则会出现sql缺失。
出现场景:在sql语句遍历之前判断List不为空,才进行下一步,这里的话会出现条件缺失,本来存在某个条件 dev_id in ('1', '2')
,这个条件就会丢失,就会没有id限制,查出任意id的数据,
解决方法:
- 其实就是不需要的数据的时候语句为
dev_id in ()
,因此加个判断如果list为空,或者为0,dev_id in ()
或者dev_id = ''
,就可以解决;
<if test="user.IdsList == null or user.IdsList.size() == 0">
and info.dev_id = ''
</if>
<if test="user.IdsList != null and user.IdsList > 0">
and info.dev_id in
<foreach item="devId" collection="user.IdsList" open="(" separator="," close=")">
#{devId}
</foreach>
</if>
- 或者遍历
List<String> IdsList
换成String[] IdsArray;
and info.dev_id in
<foreach item="devId" collection="user.IdsArray" open="(" separator="," close=")">
#{devId}
</foreach>
那么如果有初始化的时候,并且如果数组没有数据,就变成and info.dev_id in ('')