原来的写法:
select name from user_info
where 1=1
< if test="qo.ids.size>0 and qo.ids!=null">
and PK_GUID in
<foreach collection="qo.ids" index="index" item="item" open="(" separator=","
close=")">
#{item}
</foreach>
</if>
这段sql的入参对象是qo,里面有一个id集合,作用是搜索id集合里名称。
咋一看,没啥问题,但是其实在判断id集合非空的顺序上出了错:
< if test="qo.ids.size>0 and qo.ids!=null">
可以看到我们先判断了ids的条数要大于0,这样保证集合里有数据,之后再判断ids不能为空。
倒着想一下,要是ids一开始就是空的,而空对象取它的size,就会直接报异常,所以正确的判断逻辑是:
< if test="qo.ids!=null and qo.ids.size>0">
先判断ids是不是null,如果不是null,再判断它的size大小,从而确定ids集合是有值的