https://blog.csdn.net/u014231523/article/details/54235372
在使用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>
- 使用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>