Mybatis OGNL
在Structs流行的时代OGNL可是必会的数据渲染技术。它全称Object Graph Navigation Language,作用是降低对数据层访问的难度,它拥有类型转换、访问对象方法、操作集合对象等功能。目前已经很少通过OGNL来访问数据层了,目前国内大部分的ORM框架是Mybatis,而Mybatis中的动态SQL技术运用了OGNL。
Mybatis中的OGNL
不少人在Mybatis的Mapper文件中写过这样的判断:
<if test="field!='' and field!= null">and some_col = #{field}</if>
当field不为空字符并且不为null的情况下增加一个查询条件。其中 test就是一个OGNL表达式。Mybatis中的OGNL表达式主要有两种用途。
条件断言
这种是最常用的。执行动态SQL的条件断言,常用的有这些表达式:
b1 or b2条件 或b1 and b2条件 与!b1取反,也可以写作not b1b1 == b2,b1 eq b2判断两个值相等b1 != b2,b1 neq b2判断两个值不想等b1 lt b2判断b1小于(less than)b2b1 gt b2判断b1小于(greater than)b2b1 lte b2:判断b1小于等于b2b1 gte b2:判断b1大于等于b2b1 in b2判断b2包含b1b1 not in b2判断b2不包含b1
四则运算赋值
还有一些表达式用来赋值或者增强属性。经常用来做模糊搜索的 bind标签:
<bind name="nameLike" value="'%'+ name + '%'"/>
这里的value也属于OGNL表达式 e1+e2,字符串是拼接,数字的话就是加法运算,可以引申出肯定还有:
e1*e2乘法e1/e2除法e1-e2减法e1%e2取模类的内置方法
其实Mybatis的Mapper.xml中还可以使用对象的内置方法,比如需要判断一个java.util.Collection集合是否为空,可以这么写:
这里就使用了对象的内置方法<if test="collection!=null and collection.size()> 0">and some_col = #{some_val}</if>
Collection.size()。
还可以调用自定义对象CollectionUtils的静态方法来判断集合是否为空:
那么上面的public final class CollectionUtils {public static boolean isNotEmpty( Collection<?> collection) {return (collection != null && !collection.isEmpty());}}
<if>判断改为:
这里要带上类的全限定名。<if test="@cn.fcant.util.CollectionUtils@isNotEmpty(collection)">and some_col = #{some_val}</if>
取值操作
取值操作的话,如果是对象直接e.property,如果是集合或者Map可以e[index|key],通过索引或者键名来取值。分别举个例子:
其实静态属性也能取值调用,跟上面的静态方法类似:# 对象取属性user.username# 集合取元素array[1]# map 取值map['username']
对应Java代码:@cn.fcant.Cache@user
public final class Cache {public static User user = new User ("Fcant") ;}
赋值操作
上面的取值除了可以做判断还可以用来SQL参数赋值: ```xmlusername = #{username} and user_id =${userId} and id = ${user.id} and age = ${@@abs(-12345678)} and gender =${@cn.fcant.GenderEnum@MALE.ordinal()} and id=${@cn.fcant.Cache@user.userId}
``
通过${}`符号可以用OGNL表达式给SQL参数赋值。
