mybatis 之 ognl表达式

一、简介

mybatis的动态sql ,是其强大的特性之一,其实现借助了OGNL表达式。

标签如下:

if

where

trim(where,set)

foreach

ongl原理

ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator();
GoodsBiLog log = new GoodsBiLog();
log.setId(1);
boolean b = expressionEvaluator.evaluateBoolean("id!=null&&id>0", log);
System.out.println(b);

二、if

配置

<select id="find"
     resultType="GoodsBiLog">
  SELECT * FROM goods_bi_log
  WHERE 1 = 1
  <if test="id != null && id > 0">
    AND id = #{id}
  </if>
</select>

实现

GoodsBiLog log = new GoodsBiLog();
log.setId(1);
DynamicContext context = new DynamicContext(new Configuration(),log);
//静态的sql
new StaticTextSqlNode("select * from goods_bi_log where 1 = 1").apply(context);
IfSqlNode ifNode = new IfSqlNode(new StaticTextSqlNode("and id=#{id} ") , "id!=null&&id>0");
ifNode.apply(context);
System.out.println(context.getSql());

三、where

配置

<select id="find"
     resultType="GoodsBiLog">
  SELECT * FROM goods_bi_log WHERE 1 = 1
  <where>
    <if test="id != null && id > 0">
      AND id = #{id}
    </if>
  </where>
</select>

实现

        GoodsBiLog log = new GoodsBiLog();
//        log.setId(1);
//        log.setBatchNo("123");
        Configuration configuration = new Configuration();
        DynamicContext context = new DynamicContext(configuration,log);
        //静态的sql
        new StaticTextSqlNode("select * from goods_bi_log ").apply(context);
        //两个if
        IfSqlNode ifNode = new IfSqlNode(new StaticTextSqlNode("and id=#{id} ") , "id!=null&&id>0");
        IfSqlNode ifNode2 = new IfSqlNode(new StaticTextSqlNode("and batch_no=#{batchNo} ") , "batchNo!=null");
        MixedSqlNode mixedSqlNode = new MixedSqlNode(Arrays.<SqlNode>asList(ifNode ,ifNode2));
        WhereSqlNode whereSqlNode = new WhereSqlNode(configuration , mixedSqlNode);
        ChooseSqlNode chooseSqlNode = new ChooseSqlNode(Arrays.<SqlNode>asList(whereSqlNode), new StaticTextSqlNode("id = 100"));
        chooseSqlNode.apply(context);
        System.out.println(context.getSql());

四、trim(where,set)

五、foreach

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值