mybatis中如何使用OGNL表达式

来源:互联网 发布:洛杉矶黑帮知乎 编辑:程序博客网 时间:2024/05/20 08:41

在使用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如下:

<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>
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;    }}

其他的相对简单就不再举例子。

在mysql中使用mybatis进行模糊查询的方式就有下面几种:
1.使用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>

2.使用一般的方式

<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>

3.使用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>
0 0
原创粉丝点击