在 MyBatis 的 Mapper.xml 文件中的 <if> 判断是这样写的:
<select id="findAll" resultMap="RESULT_MAP">
select u.`user_id`, u.`name`, u.`sex`, u.`age`
from `user` u
where delete=0
<if test=" type == '0' ">
and u.sex = 'm'
</if>
<if test=" type == '1' ">
and u.sex = 'f'
</if>
</select>上面 Mapper.xml 文件不存在语法问题,能正常运行,但是 <if> 语句中的 SQL 代码始终得不到执行,这是因为 test="type == '0'" 或 test="type == '1'" 测试均没有通过。
通过查阅相关资料,得知,需要将 type 比较的字符串使用双引号,修改如下:
<select id="findAll" resultMap="RESULT_MAP">
select u.`user_id`, u.`name`, u.`sex`, u.`age`
from `user` u
where delete=0
<if test=' type == "0" '>
and u.sex = 'm'
</if>
<if test=' type == "1" '>
and u.sex = 'f'
</if>
</select>或者改为:
<select id="findAll" resultMap="RESULT_MAP">
select u.`user_id`, u.`name`, u.`sex`, u.`age`
from `user` u
where delete=0
<if test=" type == '0'.toString() ">
and u.sex = 'm'
</if>
<if test=" type == '1'.toString() ">
and u.sex = 'f'
</if>
</select>重启服务,问题解决了。
MyBatis 在 Mapper.xml 中使用 OGNL 表达式来解析的,在 OGNL 的表达式中,'1' 会被解析成字符(char),然而 Java 是强类型的,char 和 String 会导致不等,所以 <if> 标签中的 SQL 不会被解析。