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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值