Java之在Mybatis的xml文件中调用Java类

2023-06-05  本文已影响0人  山巅自相见

在Mybatis映射的xml文件中调用Java类,具体实现用到了OGNL表达式,表达式格式:

${@prefix@methodName(传递参数名称)}

因为需求问题,需要在运行sql的时候自动的给sql附上不固定的值,而OGNL表达式刚好解决这一问题,具体实现如下:
xml文件

<insert id="add" useGeneratedKeys="true" >
  insert into testTable (field_one)
  values (${@com.service.impl.IyunBlessingRecordServiceImpl@testMethed(fieldOne)})
</insert>

Java类

public static String testMethed(String fieldOne) throws ParseException {
  // 代码
  return; // String类型
}

上述xml代码中rankScoring这一字段的值就是引用了com.service.impl.IyunBlessingRecordServiceImpl这个类中的dongAo静态方法,括号中的值将作为方法的请求参数,方法的响应参数会成为sql中的字段值。
假如rankScoring的值为1,类中的方法为这样:

public static String testMethed(String fieldOne) throws ParseException {
  rankScoring ++;
  return rankScoring ;
}

那么sql编译完后为这样

insert into testTable (field_one) values (‘2’)

在删除、修改和查询的sql中同样生效。

注意:方法必须为静态方法、

Mybatis常用的OGNL表达式如下
1、e1 or e2:或

<if test="userEmail != null or userEmail == '1'">
</if>

2、e1 and e2:且

<if test="userEmail != null and userEmail != ''">
</if>

3、e1 == e2 或e1 eq e2:相等

<if test="userEmail == null and userEmail == ''">
</if>

4、e1 != e2 或 e1 neq e2:不等

<if test="userEmail != null and userEmail != ''">
</if>

5、e1 lt e2:小于

<if test="age lt 10">
</if>

6、e1 lte e2:小于等于
7、e1 gt e2:大于
8、e1 gte e2:大于等于
9、 e1 + e2(加),e1 - e2(减),e1 * e2(乘),e1/e2(除),e1%e2(余)
10、!e或not e:非,取反

上一篇 下一篇

猜你喜欢

热点阅读