问题场景:
看如下sql 你觉得会不会生效
select
*
from institution_balance
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="balance == '1'">
and balance = #{balance}
</if>
</where>
结果:
这个代码无论balance传递"1"还是"2",这个都不会生效,会直接略过这个if判断
原因:
因为mybatis是用OGNL表达式来解析的,在OGNL的表达式中,'1’或’2’这种类的都会被解析成字符,而java又是强类型的,字符和单个字符串是不相等的,所以会导致两边的类型不相等,所以标签中的sql不会被解析同个。要想相等,必须两边都是相同的类型。
解决方案
解决方法有三种,分别如下:
1.将单引号换为双引号,把test的引号换成单引号,里面的判断换成双引号即可
select
*
from institution_balance
<where>
<if test="id != null">
and id = #{id}
</if>
-- 这里交换了符号顺序
<if test='balance == "1"'>
and balance = #{balance}
</if>
</where>
2.使用toString强转,把字符类型使用toString()方法强转为字符串类型
select
*
from institution_balance
<where>
<if test="id != null">
and id = #{id}
</if>
-- 这里加了toString()方法
<if test="balance == '1'.toString()">
and balance = #{balance}
</if>
</where>
3.将字符换成Integer类型,在传递参数时就传递Integer类型,使用Integer类型进行判断
select
*
from institution_balance
<where>
<if test="id != null">
and id = #{id}
</if>
-- 这里去掉了单引号
<if test="balance == 1">
and balance = #{balance}
</if>
</where>