MyBatis mapper.xml中使用静态常量或者静态方法

使用MyBatis技术,书写mapper.xml时,如果在其中的ognl表达式或者sql中直接使用一些数字或者字符串的话,会造成难以维护的问题。在Java编码中,我们通常会把这些数字或者字符串定义在常量类或者接口中,如果在mapper.xml中也可以使用这些常量就比较好了。还好MybBatis是支持这样的需求的。

包名:com.test.util
类名:DateUtil
静态变量:CURRENT_YEAR
静态方法:sLeapYear

静态方法

package com.test.util;

public class DateUtil {

    public static final String CURRENT_YEAR = "id";

    public static String sLeapYear(String who) {
        return who;
    }
}

mapper.xml

// 引用静态常量
<select id="test">
        select *
        from user
        where port = ${@com.test.util.DateUtil@CURRENT_YEAR}
</select>

// 引用静态方法
<select id="test">
        select *
        from user
        where port = ${@com.test.util.DateUtil@sLeapYear()}
</select>

// 当我们使用<if test=""></if>判断标签时,不用使用${}进行拼接,直接使用@加上路径就可作为条件判断使用
<select id="test">
        select *
        from user
        <if test = "@com.test.util.DateUtil@sLeapYear()">
           where port = 1 
        </if>
        <if test = "!(@com.test.util.DateUtil@sLeapYear())">
           where port = 1 
        </if>
</select>

版权声明:本文为weixin_52334381原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。