在使用mybatis时经常使用到OGNL表达式。特别是在使用动态sql查询时。
下面看下一些常用的OGNL(详情请点这里–官网介绍):
表达式e1,e2
- e1 or e2
- e1 and e2
- e1 == e2, e1 eq e2
- e1 != e2, e1 neq e2
- e1 < e2, e1 lt e2
- e1 <= e2, e1 lte e2
- e1 > e2, e1 gt e2
- e1 >= e2, e1 gte e2
- e1 in e2
- e1 not in e2
- ! e, not e,e instanceof class
- e.method(args)调用对象方法
- e.property调用对象属性
- e1[ e2 ] 按索引取值,list,数组和map
- @class@method(args) 调用静态方法
- @class@field 调用静态常量
这里举个简单例子说明下@class@method(args)和@class@field的用法:
sql如下:
- 静态方法@class@method(args)
<select id="select" parameterType="com.xingguo.springboot.model.User" resultType="com.xingguo.springboot.model.User">
select username,password from t_user
where 1=1
<choose>
<!--调用静态方法 -->
<when test="@com.xingguo.springboot.model.TestConstant@checkStatus(state,0)">
<!--调用静态常量 -->
AND state = ${@com.xingguo.springboot.model.TestConstant@STATUS_0}
</when>
<otherwise>
AND state = ${@com.xingguo.springboot.model.TestConstant@STATUS_1}
</otherwise>
</choose>
</select>
- 静态常量@class@field
package com.xingguo.springboot.model;
public class TestConstant {
//静态常量
public static final int STATUS_0 = 0;
public static final int STATUS_1 = 1;
//静态方法
public static Boolean checkStatus(int sourceStatus,int targetStatus){
return sourceStatus == targetStatus;
}
public static final List<Integer> STATES= Lists.newArrayList(STATUS_0,
STATUS_1);
}
如果是参数是List的情况:
<select id="selectCount" resultType="int">
select COUNT(1) from t_user
where state in
<foreach collection="@com.xingguo.springboot.model.TestConstant@STATES"
item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
其他的相对简单就不再举例子。
在mysql中使用mybatis进行模糊查询的方式就有下面几种:
- 使用OGNL
<select id="select" parameterType="com.xingguo.springboot.model.User" resultType="com.xingguo.springboot.model.User">
select username,password from t_user
where 1=1
<!-- OGNL处理${这里的表达式}的结果值 -->
<if test="username != null and username != ''">
and username like '${'%' + username + '%'}'
</if>
</select>
- 使用一般的方式
<select id="select" parameterType="com.xingguo.springboot.model.User" resultType="com.xingguo.springboot.model.User">
select username,password from t_user
<where>
<!-- 使用concat -->
<if test="username != null and username != ''">
username like concat('%', #{username}, '%')
</if>
</where>
</select>
- 使用bind
<select id="select" parameterType="com.xingguo.springboot.model.User" resultType="com.xingguo.springboot.model.User">
select username,password from t_user
<bind name="nameLike" value="'%' + username + '%'"/>
<where>
<if test="username != null and username != ''">
username like #{nameLike}
</if>
</where>