mybatis 之 ognl表达式
Posted better_hui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于mybatis 之 ognl表达式的主要内容,如果未能解决你的问题,请参考以下文章