今天团队在代码走查时发现了一个mybatis作为dao层查询中存在参数使用前校验不全的问题修改后却触发了另外一个错误,情况如下。
走查时代码如下(existIds传入的一个集合,只判断了未定义的情况,在集合有定义但长度为0时会报错):
SELECT
<include refid="Base_Column_List"/>
FROM SYS_BIZAPP
WHERE 1=1
<if test="existIds!=null">
AND ID NOT IN (
<foreach collection="existIds" item="item" index="index" separator=",">
#{item,jdbcType=VARCHAR}
</foreach>
)
</if>
经过提示开发修改提交,我们再次检查修改情况时发现代码如下。
SELECT
<include refid="Base_Column_List"/>
FROM SYS_BIZAPP
WHERE 1=1
<if test="existIds!=null and existIds!='' ">
AND ID NOT IN (
<foreach collection="existIds" item="item" index="index" separator=",">
#{item,jdbcType=VARCHAR}
</foreach>
)
</if>
该查询语句在执行过程中会发生
java.lang.IllegalArgumentException: invalid comparison: java.util.ArrayList and java.lang.String的情况。
因为错误的使用空字符串的判断方式来判断集合是否为空。需要将判断方式改为size>0即可。最终修改代码如下:
SELECT
<include refid="Base_Column_List"/>
FROM SYS_BIZAPP
WHERE 1=1
<if test="existIds!=null and existIds.size>0 ">
AND ID NOT IN (
<foreach collection="existIds" item="item" index="index" separator=",">
#{item,jdbcType=VARCHAR}
</foreach>
)
</if>
本文记录了一次代码走查中发现的MyBatis DAO层查询参数校验不足问题,详细描述了从最初的问题发现到错误修改方案,再到正确解决的过程。强调了在集合参数校验时,应使用size()方法而非与空字符串比较。
3366

被折叠的 条评论
为什么被折叠?



