【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 如果直接将 ...
随机推荐
- redis集群搭建-3.0/4.0版本
1. Redis的安装 1.1. Redis的安装 Redis是c语言开发的. 安装redis需要c语言的编译环境.如果没有gcc需要在线安装.yum install gcc-c++ 安装步骤: 第 ...
- AJ整理问题之:copy,对象自定义copy 什么是property
AJ分享,必须精品 copy copy的正目的 copy 目的:建立一个副本,彼此修改,各不干扰 Copy(不可变)和MutableCopy(可变)针对Foundation框架的数据类型. 对于自定义 ...
- HttpWebRequest在Post的时候,遇到特殊符号+号(加号)变成空格了
今天在调用一个外部接口的时候遇到一个问题,外部接口说要用FOMR的POST方法提交. OK,没问题,我加了个ASPX页面,里面加了个FORM表单和一些元素,提交,返回值成功.注意看下面这一句:但返回值 ...
- R - Cow and Message CodeForces - 1307C
思路对了,但是不会写. 等差数列长度不是1就是2,所以不是一个字母就是俩字母,一开始写的时候直接枚举两个字母,然后让次数相乘.这样是不对的,比如abaabb,字母ab的个数应该是3+2+2,因该是每一 ...
- Go gRPC进阶-proto数据验证(九)
前言 上篇介绍了go-grpc-middleware的grpc_zap.grpc_auth和grpc_recovery使用,本篇将介绍grpc_validator,它可以对gRPC数据的输入和输出进行 ...
- Os-hackNos-1靶机过关记录
靶机地址:172.16.1.198(或112) kali地址:172.16.1.108 1 信息收集 靶机界面如下 简单查看 OS:Ubuntu Web:Apache2.4.18 尝试端口扫描 开放 ...
- Springboot:员工管理之删除员工及退出登录(十(9))
springboot2.2.6 delete请求报错,降至2.1.11功能可用 原因未知 构建员工删除请求 com\springboot\controller\EmployeeController.j ...
- Web中间件常见漏洞
IIS Internet Information Services--windows 解析漏洞 IIS 6.x 基于文件名:该版本默认会将 *.asp;.jpg 此种格式的文件名,当成 Asp 解析, ...
- 以命令行界面启动 Ubuntu
1. /etc/default/grub 将GRUB_CMDLINE_LINUX_DEFAULT一行中改为"quiet splash 3" 2. update-grub 3. 重启
- SpringBoot中使用Fastjson/Jackson对JSON序列化格式化输出的若干问题
来源 :https://my.oschina.net/Adven/blog/3036567 使用springboot-web编写rest接口,接口需要返回json数据,目前国内比较常用的fastjso ...