【mybatis】IF判断的坑
http://cheng-xinwei.iteye.com/blog/2008200
最近在项目使用mybatis中碰到个问题
<if test="type=='y'">
and status = 0
</if>
当传入的type的值为y的时候,if判断内的sql也不会执行,抱着这个疑问就去看了mybatis是怎么解析sql的。下面我们一起来看一下mybatis 的执行过程。
DefaultSqlSession.class 121行
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
在 executor.query(ms, wrapCollection(parameter), rowBounds, handler);
执行到BaseExecutor.class执行器中的query方法
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameter);
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
在query的方法中看到boundSql,是通过 ms.getBoundSql(parameter);获取的。
再点进去可以看到MappedStatement.class类中的getBoundSql方法
public BoundSql getBoundSql(Object parameterObject) {
BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings == null || parameterMappings.size() <= 0) {
boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
}
// check for nested result maps in parameter mappings (issue #30)
for (ParameterMapping pm : boundSql.getParameterMappings()) {
String rmId = pm.getResultMapId();
if (rmId != null) {
ResultMap rm = configuration.getResultMap(rmId);
if (rm != null) {
hasNestedResultMaps |= rm.hasNestedResultMaps();
}
}
}
return boundSql;
}
看到其中有sqlSource.getBoundSql(parameterObject); sqlsource是一个接口。
/**
*
* This bean represets the content of a mapped statement read from an XML file
* or an annotation. It creates the SQL that will be passed to the database out
* of the input parameter received from the user.
*
*/
public interface SqlSource {
BoundSql getBoundSql(Object parameterObject);
}
类中getBoundSql是一个核心方法,mybatis 也是通过这个方法来为我们构建sql。BoundSql 对象其中保存了经过参数解析,以及判断解析完成sql语句。比如<if> <choose> <when> 都回在这一层完成,具体的完成方法往下看,那最常用sqlSource的实现类是DynamicSqlSource.class
public class DynamicSqlSource implements SqlSource {
private Configuration configuration;
private SqlNode rootSqlNode;
public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) {
this.configuration = configuration;
this.rootSqlNode = rootSqlNode;
}
public BoundSql getBoundSql(Object parameterObject) {
DynamicContext context = new DynamicContext(configuration, parameterObject);
rootSqlNode.apply(context);
SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
for (Map.Entry<String, Object> entry : context.getBindings().entrySet()) {
boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
}
return boundSql;
}
}
核心方法是调用了rootSqlNode.apply(context); rootSqlNode是一个接口
public interface SqlNode {
boolean apply(DynamicContext context);
}
可以看到类中 rootSqlNode.apply(context); 的方法执行就是一个递归的调用,通过不同的
实现类执行不同的标签,每一次appll是完成了我们<></>一次标签中的sql创建,计算出标签中的那一段sql,mybatis通过不停的递归调用,来为我们完成了整个sql的拼接。那我们主要来看IF的实现类IfSqlNode.class
public class IfSqlNode implements SqlNode {
private ExpressionEvaluator evaluator;
private String test;
private SqlNode contents;
public IfSqlNode(SqlNode contents, String test) {
this.test = test;
this.contents = contents;
this.evaluator = new ExpressionEvaluator();
}
public boolean apply(DynamicContext context) {
if (evaluator.evaluateBoolean(test, context.getBindings())) {
contents.apply(context);
return true;
}
return false;
}
}
可以看到IF的实现中,执行了 if (evaluator.evaluateBoolean(test, context.getBindings())) 如果返回是false的话直接返回,否则继续递归解析IF标签以下的标签,并且返回true。那继续来看 evaluator.evaluateBoolean 的方法
public class ExpressionEvaluator {
public boolean evaluateBoolean(String expression, Object parameterObject) {
Object value = OgnlCache.getValue(expression, parameterObject);
if (value instanceof Boolean) return (Boolean) value;
if (value instanceof Number) return !new BigDecimal(String.valueOf(value)).equals(BigDecimal.ZERO);
return value != null;
}
关键点就在于这里,在OgnlCache.getValue中调用了Ognl.getValue,看到这里恍然大悟,mybatis是使用的OGNL表达式来进行解析的,在OGNL的表达式中,'y'会被解析成字符,因为java是强类型的,char 和 一个string 会导致不等。所以if标签中的sql不会被解析。具体的请参照 OGNL 表达式的语法。到这里,上面的问题终于解决了,只需要把代码修改成:
<if test='type=="y"'>
and status = 0
</if>
就可以执行了,这样"y"解析出来是一个字符串,两者相等!
【mybatis】IF判断的坑的更多相关文章
- Mybatis if判断的坑
具体情况参考这两篇文章: http://cheng-xinwei.iteye.com/blog/2008200 http://www.cnblogs.com/tv151579/p/3297691.ht ...
- 关于MyBatis传入String用于test判断的坑
不要在心情糟糕的时候写代码,能坑死自己. 今天码代码的时候出现一个问题,脾气暴躁到砸桌子, 在Mybatis传入参数为String并且用 if test 判断的过程中发现 <if test=&q ...
- mybatis if判断两个值是否相等存在的坑啊
1.使用“==”比较 字符类型 的值 用“==”比较的使用场景: 不管你用的什么类型的变量,只要变量的值是字符类型就用“==” 产生原因: 在mybatis中如果<if>标签用一个“=”判 ...
- Mybatis的失误填坑-java.lang.Integer cannot be cast to java.lang.String
Mybatis的CRUD小Demo 为方便查看每次的增删改结果,封装了查询,用来显示数据库的记录: public static void showInfo(){ SqlSession session ...
- Mybatis if 判断等于一个字符串
在做开发的时候遇到这样一个问题:当传入的type的值为y的时候,if判断内的sql也不会执行. <if test="type=='y'"> and status ...
- mybatis匹配字符串的坑
where语句中我们经常会做一些字符串的判断,当传入的字符串参数为纯数字时,在mybatis的条件语句test里匹配全数字字符串需要注意会有如下现象: 所以里面的字符串需要加单引号,mybatis是匹 ...
- MyBatis 一级缓存避坑
MyBatis 一级缓存(MyBaits 称其为 Local Cache)无法关闭,但是有两种级别可选: package org.apache.ibatis.session; /** * @autho ...
- MyBatis正在爬的坑
换了份工作,开始接触Mybatis,开一篇文章记录一下自己遇到的坑 2018-06-20 今天遇到了一个问题,编好的sql语句在数据库可以执行但是写到程序里边就GG,什么问题呢?一直纠结在程序哪里写错 ...
- LocalDatetime 与 mybatis、json的坑
总所周知,localdatetime是jdk8 推出的关于日期计算非常方便地一个类,一旦开始用上就欲罢不能.但是在使用的时候,坑还是蛮多的. 一.mybatis与LocalDatetime 如果直接将 ...
随机推荐
- 怎样才能拥有营销号生成器功能?python帮你实现
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取http ...
- Linux下安装Redis4.0版本(简便方法)
Redis介绍: Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点: Redis支持数据的持久 ...
- mysql搭建亿级cmd5数据库,毫秒级查询 完全过程
前言: 最近也在玩数据库,感觉普通机子搞数据库,还是差了点,全文查找,慢的要查一分钟更久. 但是搞cmd5库很不错,亿级数据库,毫秒级. qq 944520563好吧,下面开始,首先你得需要一个mys ...
- mongo基础
以下如有任何问题,直接到官方操作文档左上角搜索框搜索 安装 On Windows, this path is on the drive from which you start MongoDB. Fo ...
- [转]PHP利用PCRE回溯次数限制绕过某些安全限制
这次Code-Breaking Puzzles中我出了一道看似很简单的题目pcrewaf,将其代码简化如下: <?php function is_php($data){ return preg_ ...
- testNG 常用的注解
常用注解介绍: @BeforeSuite 在该套件的所有测试都运行在注释的方法之前,仅运行一次 @AftereSuite 在该套件的所有测试都运行在注释方法之后,仅运行一次 @BeforeClass ...
- EF-相关查询(逐渐完善)
linq查询方式 多条件查询 内连接 左连接 可以执行sql含事务
- 当td中文字过长时,显示为省略号
当表格中的文字过长时,可选择已省略号显示.这里是用js实现的.首先获取td中的文字长度(innerText.length),如果长度超过了设定的长度,则截取内容,加上省略号显示.示例代码如下: $(f ...
- 挑战全网最幽默的Vuex系列教程:第五讲 Vuex的小帮手
先说两句 前面已经讲完了 Vuex 下的 State.Getter.Mutation 及 Action 这四驾马车,不知道大家是否已经理解.当然,要想真正熟练掌握的话,还是需要不断的练习和动手实践才行 ...
- Android 中 OkHttp 三步实现生命周期绑定
简介 OkHttps 是 OkHttp 增强版的超轻量封装包. 和 Retrofit 相比,它更加轻量(只有 59Kb),是 Retrofit (124Kb)的一半,而且更加的开箱即用,API 更加自 ...