Mybatis中的OGNL使用總結(jié)
Mybatis中常用的OGNL表達式有以下:
e1 or e2
e1 and e2
e1 == e2,e1 eq e2
e1 != e2,e1 neq e2
e1 lt e2:小于
e1 lte e2:小于等于,其他gt(大于),gte(大于等于)
e1 in e2
e1 not in e2
e1 + e2,e1 * e2,e1/e2,e1 - e2,e1%e2
!e,not e:非,求反
e.method(args)調(diào)用對象方法
e.property對象屬性值
e1[ e2 ]按索引取值,List,數(shù)組和Map
@class@method(args)調(diào)用類的靜態(tài)方法
@class@field調(diào)用類的靜態(tài)字段值
在一定意義上說,mybatis中的動態(tài)sql也是基于OGNL表達式的。其中常用的元素有如下幾種:
if
choose(when,otherwise)
trim
where
set
foreach
OGNL在mybatis中的應(yīng)用,主要有兩種:
OGNL的調(diào)用靜態(tài)方法的示例:
<select id="getRecentQuestionTitle" parameterType="java.lang.String" resultType="java.lang.String">
select title from song_question where questionState = #{value}
<if test="@Ognl@isSolve(value[0],0)">
order by questionTime desc
</if>
<if test="@Ognl@isSolve(value[0],1)">
order by answerTime desc
</if>
limit 0,1
</select>
靜態(tài)方法如下:
public static boolean isSolve(Object o,String soleState){
if(o == null)
return false;
String str = null;
if(o instanceof String[]){
String[]objects = (String[])o;
str = objects[0];
}else if(o instanceof Character){
Character c = (Character) o;
str = Character.toString(c);
}
if(StringUtils.equals(str, soleState))
return true;
return false;
}
如果值為0,則order by questionTime desc 根據(jù)字段questionTime排序。
如果值為1,則order by answerTime desc根據(jù)字段answerTime排序。

Mybatis中的OGNL表達式(一)

Mybatis中的OGNL表達式(二)