MyBatis 中 <if> 判断字符串是否相等失效

本文将解决在 MyBatis 的 Mapper.xml 文件中使用 <if> 标签的 test 属性测试字符串是否相等,但是测试未通过,也不存在语法问题。

在 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 不会被解析。

业精于勤,荒于嬉。——韩愈《进学解》
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号