mybatis 映射文件中,if标签判断字符串相等,两种方式:
因为mybatis映射文件,是使用的ognl表达式,所以在判断字符串sex变量是否是字符串Y的时候,
<if test="sex==Y.toString()">
<if test = sex== "Y">
注意:
不能使用
<if test="sex==Y">
and 1=1
</if>
因为mybatis会把Y解析为字符,所以不能这样写 会报NumberFormatException
MyBatis是使用的OGNL表达式来进行解析的,这个地方有一个坑需要注意下,单引号内有一个字符的情况下,OGNL会将其以 java 中的 char 类型进行解析,那么此时 char 类型与参数 String 类型用等号进行比较的时候结果都是false。解决方案也很简单,就是将 test 中的单个字符用双引号括起来。
<where>
/*不行*/
<if test="qryStr==Y">
and counts=1
</if>
/*可以*/
<if test="qryStr==Y.toString()">
and counts=1
</if>
/*可以*/
<if test=qryStr=="Y">
and counts=2
</if>
</where>