mybits 笔记

2020-02-20

if 比较两个字符串

<trim prefix="where">
                city_code = #{city_code}
                <if test="age == '0'">AND (age IS NULL OR age = '0')</if>
                <if test="age != '0'">AND (age IS NULL OR age = '0' OR age = #{age})</if>
</trim>

上面 if 判断age字符串是否等于字符串0  ;age为 "0" 时,执行的也是第二条 sql;

原来 单引号是字符类型(char) ,无法和字符串类型相等,所以第一个sql条件不会报错,但也永远不会成立;

解决方法1:

用双引号包围要比较的字符串内容

<trim prefix="where">
                city_code = #{city_code}
                <if test='age == "0"'>AND (age IS NULL OR age = '0')</if>
                <if test='age != "0"'>AND (age IS NULL OR age = '0' OR age = #{age})</if>
</trim>

解决方法2:

.toString()

<trim prefix="where">
                city_code = #{city_code}
                <if test="age == '0'.toString()">AND (age IS NULL OR age = '0')</if>
                <if test="age != '0'.toString()">AND (age IS NULL OR age = '0' OR age = #{age})</if>
</trim>

延伸:if 比较两个值相等:"==" 和 "=";如果使用"="比较,mybits会自动把等号两边的值转为数据类型(Number),所以如果是两个数字,那可以直接用"=";如果是两个字符串,必须用"==";


原文地址:https://www.cnblogs.com/javencs/p/12335858.html