mybatis 使用ognl

@Ognl@isNotEmpty() for String,Array,Collection,Map Test

now, test empty string test. must use:

<if test="userId != null && ''.equals(userId)">
and user_id = #{userId}
</if>

but, OGNL support Calling Static Methods.
http://www.opensymphony.com/ognl/html/LanguageGuide/staticMethods.html

so, we can use this for test empty String,Array,Collection,Map.
look like this:

<if test="@Ognl@isNotEmpty(userId)">
        and user_id = #{userId}
</if>




source code:

public class Ognl {

/**
* test for Map,Collection,String,Array isEmpty
* @param o
* @return
*/
public static boolean isEmpty(Object o) throws IllegalArgumentException {
if(o == null) return true;

if(o instanceof String) {
if(((String)o).length() == 0){
return true;
}
} else if(o instanceof Collection) {
if(((Collection)o).isEmpty()){
return true;
}
} else if(o.getClass().isArray()) {
if(Array.getLength(o) == 0){
return true;
}
} else if(o instanceof Map) {
if(((Map)o).isEmpty()){
return true;
}
}else {
return false;
}

return false;
}

/**
* test for Map,Collection,String,Array isNotEmpty
* @param c
* @return
*/
public static boolean isNotEmpty(Object o) {
return !isEmpty(o);
}
}


and will put this class to "default package".

 

要把ognl.java文件放到default package下,否则会报错。。。

错误:ibatis Method "isNotEmpty" failed for object Ognl [java.lang.ClassNotFoundException: java.lang.Ognl]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
OGNL(Object-Graph Navigation Language,对象图导航语言)是一个强大的表达式语言,可以用于Java的各种应用程序中,包括Struts、JavaServer Faces、JavaServer Pages等。在Mybatis中,OGNL表达式可以用于Mapper XML文件中的各种标签中,例如`<if>`、`<where>`、`<set>`、`<foreach>`等标签中。 OGNL表达式可以用于获取Java对象的属性值、调用Java对象的方法、进行算术运算、比较运算、逻辑运算等。例如: ```xml <select id="selectByCondition" resultType="com.example.User"> select * from user where name like #{keyword} and age >= #{minAge} <if test="maxAge != null"> and age <= #{maxAge} </if> </select> ``` 在这个例子中,`#{keyword}`、`#{minAge}`、`#{maxAge}`都是OGNL表达式,表示获取Java对象中的属性值。例如,如果传入的参数对象是一个`User`对象,那么`#{keyword}`可以表示`user.getKeyword()`方法的返回值,`#{minAge}`可以表示`user.getMinAge()`方法的返回值。 在OGNL表达式中,还可以进行算术运算、比较运算、逻辑运算等。例如,`age >= #{minAge}`表示将`age`和`#{minAge}`进行比较,判断`age`是否大于等于`#{minAge}`;`age <= #{maxAge}`表示将`age`和`#{maxAge}`进行比较,判断`age`是否小于等于`#{maxAge}`。 除了基本的运算符和表达式,OGNL还提供了丰富的函数和操作符,例如`in`操作符、`not`操作符、`contains`函数、`size`函数等。这些函数和操作符可以方便地进行集合操作、字符串操作等。在使用OGNL表达式时,需要注意语法的正确性和安全性,以避免可能的安全漏洞。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值