MyBatis if test 判断字符串相等不生效

  采用 MyBatis 框架操作 MySQL 数据库时,判断传入的字符串 priceFlag 值为"0"时,按照 price 属性降序排列,如下 xml 语句未生效:

<if test="priceFlag != null and priceFlag == '0'">
      ORDER BY price DESC
</if>

  原因分析:
  MyBatis 是使用 OGNL 表达式来进行解析的,在 OGNL 表达式中,'0’会被解析成字符,因为 java 是强类型的,char 和 String 不等,所以 if 标签中的 SQL 不会被解析。

  解决方法:
  解决这个问题,可以把 if test 判断语句修改成如下几种方式中的任何一种:

<if test='"0" == priceFlag'>

  或者

<if test='"0".equals(priceFlag)'>

  或者

<if test="'0'.toString() == priceFlag">

  修改完成后,SQL 语句就可以被解析了。

猜你喜欢

转载自blog.csdn.net/piaoranyuji/article/details/108280023