mybatis if test条件判断语句中的判断问题实例分析

发布时间:2022-03-14 09:24:42 作者:iii
来源:亿速云 阅读:366

本文小编为大家详细介绍“mybatis if test条件判断语句中的判断问题实例分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“mybatis if test条件判断语句中的判断问题实例分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

if test条件判断语句中的判断问题

写这个主要是描述在mybatis中要注意的问题,很不幸,自己没注意,跳坑了。

我在mybatis中定义的sql语句如下

<if test="facilityOccupied != null and facilityOccupied != '' and facilityOccupied == 1 ">
                and z.serviceCount = 1
            </if>    
            <if test="facilityOccupied != null and facilityOccupied != '' and facilityOccupied == 0 ">
                and z.serviceCount = 0
            </if>

可以看到这里只是对传入参数一个简单的判断。

controller层传入一个Integer类型的facilityOccupied参数。

表面上看没什么问题,当传入facilityOccupied = 1,测试结果很意外,它查询了所有的结果,也就是说它没有符合这个判断facilityOccupied == 1 。

换一种写法,在controller层中将传入参数facilityOccupied改为String类型的,通过查询结果可以看出它符合facilityOccupied == 1 这个判断条件。

或使用equals()

<if test="facilityOccupied != null and facilityOccupied != '' and facilityOccupied.equals(1)">
                and z.serviceCount = 1
            </if>    
            <if test="facilityOccupied != null and facilityOccupied != '' and facilityOccupied.equals(0)">
                and z.serviceCount = 0
            </if>

所以,总结起来怎么说,在这个地方比较的并不是数值大小,而是物理地址,这个双引号里面的1不是int类型也不是integer类型,而是String字符串类型,啊多么痛的领悟。

补充一下,test中eq 和 == 效果一样,比较的是地址,所以比较值最好使用equals()。

mybatis 中if test判断大坑

【<if test="takeWay == '0'">】mybatis的if判断

单个的字符要写到双引号里面才行,改为<if test='takeWay == "1"'>或者改为<if test="takeWay == '1'.toString() ">

.xml文件的部分代码

<insert id="insertDelivery" parameterType="com.zuci.request.DeliveryPreferenceReq">     
    insert cx_customer_deliverypreference     
    <trim prefix="(" suffix=")" suffixOverrides=",">           
        .... 此处省略       
        <if test="takeWay == '1' and workday != null ">         
            WORKDAY,       
        </if>       
        ....     
    </trim>
         
    <trim prefix="values (" suffix=")" suffixOverrides=",">          
        .... 此处省略          
        <if test="takeWay == '1' and workday != null ">            
            #{workday, jdbcType=VARCHAR},     
        </if>      
        ....   
    </trim>
</insert>

takeWay == “1”处出错,导致不执行if判断中的sql,运行程序不报错,没有任何提示。去掉takeWay == “1” and 则可执行。对此我百思不得其解,

因为自己有写过如下代码,是没错的。

<if test="messageType == 'senderReceiveSuccess' ">
      ......
</if>

原因是:mybatis是用OGNL表达式来解析的,在OGNL的表达式中,&rsquo;1&rsquo;会被解析成字符,java是强类型的,char 和 一个string 会导致不等,所以if标签中的sql不会被解析。

总结下使用方法:单个的字符要写到双引号里面或者使用.toString()才行!

使用Mybatis时,常常会判断属性是否为空

POJO

private Integer status;//状态,可能为0、1、2、3。

Mapper XML

<sql>
  <trim prefix="where" prefixOverrides="and | or ">
      //...省略其他
      <if test="status != null and status !=''">and status = #{status}</if> 
  <trim prefix="where" prefixOverrides="and | or ">
</sql>

为了避免这个问题,改成下面这样写,去掉对空字符的判断,就解决了该问题

<if test="status != null">and status = #{status}</if>

原因分析

通过Debug MyBatis源码顺藤摸瓜找到了IfSqlNode类,该类用来处理动态SQL的<if>节点,方法public boolean apply(DynamicContext context)用来构造节点内的SQL语句。if (evaluator.evaluateBoolean(test, context.getBindings())该代码便是解析<if test="status !=null and status !=''">test内表达式的关键,如果表达式为true则拼接SQL,否则忽略。

public class IfSqlNode implements SqlNode {
  private ExpressionEvaluator evaluator;
  private String test;
  private SqlNode contents;
  public IfSqlNode(SqlNode contents, String test) {
    this.test = test;
    this.contents = contents;
    this.evaluator = new ExpressionEvaluator();
  }
  public boolean apply(DynamicContext context) {
    if (evaluator.evaluateBoolean(test, context.getBindings())) {
      contents.apply(context);
      return true;
    }
    return false;
  }
}

打开ExpressionEvaluator 类,发现解析表达式使用的是OGNL,如果你使用过古老的Struts框架你应该对它不陌生。通过OgnlCache.getValue(expression, parameterObject);可以看到表达式的值是从缓存中获取的,由此可知MyBatis竟然对表达式也做了缓存,以提高性能。

public class ExpressionEvaluator {  
  public boolean evaluateBoolean(String expression, Object parameterObject) {  
    Object value = OgnlCache.getValue(expression, parameterObject);  
    if (value instanceof Boolean) return (Boolean) value;  
    if (value instanceof Number) return !new BigDecimal(String.valueOf(value)).equals(BigDecimal.ZERO);  
    return value != null;  
  }

跟进去看看,终于找到了解析表达式的方法private static Object parseExpression(String expression),该方法会先从缓存取值,如果没有便进行解析并放入缓存中,然后调用Ognl.getValue(parseExpression(expression), root)获得表达式的值。

public class OgnlCache {
  private static final Map<String, ognl.Node> expressionCache = new ConcurrentHashMap<String, ognl.Node>();
  public static Object getValue(String expression, Object root) throws OgnlException {
    return Ognl.getValue(parseExpression(expression), root);
  }
  private static Object parseExpression(String expression) throws OgnlException {
    try {
      Node node = expressionCache.get(expression);
      if (node == null) {
        node = new OgnlParser(new StringReader(expression)).topLevelExpression();
        expressionCache.put(expression, node);
      }
      return node;
    } catch (ParseException e) {
      throw new ExpressionSyntaxException(expression, e);
    } catch (TokenMgrError e) {
      throw new ExpressionSyntaxException(expression, e);
    }
  }

至于Ognl.getValue(parseExpression(expression), root)是如何运作的,如果你有兴趣可以自行跟下去一探究竟,本文就不赘述了。到此为止,我们已经知道MyBatis的表达式是用OGNL处理的了,这一点已经够了。下面我们去OGNL官网看看是不是我们的表达式语法有问题从而导致该问题的发生。

Interpreting Objects as Booleans

Any object can be used where a boolean is required. OGNL interprets objects as booleans like this:

If the object is a Boolean, its value is extracted and returned;

If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false;

If the object is a Character, its boolean value is true if and only if its char value is non-zero;

Otherwise, its boolean value is true if and only if it is non-null.

果然,如果对象是一个Number类型,值为0时将被解析为false,否则为true,浮点型0.00也是如此。OGNL对于boolean的定义和JavaScript有点像,即'' == 0 == false。这也就不难理解<if test="status != null and status !=''">and status = #{status}</if>当status=0时出现的问题了,显然0!=''是不成立的,导致表达式的值为false。

将表达式修改为<if test="status != null">and status = #{status}</if>该问题便迎刃而解。该问题的根源还是来自编码的不规范,只有String类型才需要判断是否!='',其他类型完全没有这个必要,可能是开发人员为了省事直接复制上一行拿过来改一改或是所使用的MyBatis生成工具不严谨导致该问题的发生。

这里有必要再提一个“坑”,如果你有类似于String str ="A"; <if test="str!= null and str == 'A'">这样的写法时,你要小心了。因为单引号内如果为单个字符时,OGNL将会识别为Java 中的 char类型,显然String 类型与char类型做==运算会返回false,从而导致表达式不成立。解决方法很简单,修改为<if test='str!= null and str == "A"'>即可。

读到这里,这篇“mybatis if test条件判断语句中的判断问题实例分析”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. makefile(03)_条件判断
  2. shell 条件判断

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis if test

上一篇:如何使用Java SpringBoot实现文件上传功能

下一篇:Java中Date类如何设置与操作时间

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》