公众号搜索“码路印记”,点关注不迷路!
这篇文章的标题本来该延续之前几篇的传统,叫做“Mybatis源码之ParameterHandler”,但是这个名字不足以覆盖这篇文章的内容,读完你就会知道ParameterHandler在设置过程中仅有那么一丁点的部分。
根据我的理解,Mybatis参数设置过程分为参数解析处理、动态SQL转为静态SQL、预编译参数赋值几个步骤,其中动态SQL转为静态SQL的过程中会涉及预编译${}
参数赋值和预编译参数的解析工作。本文将从一个简单的示例出发了解Mybatis参数设置的全部流程,文章会涉及一些常见的问题:
${}
占位符的处理流程;#{}
占位符的处理流程;- ParameterHandler#setParameters的执行流程;
从Demo开始
这个demo是在原来的基础上进行了改造,不过也仅仅是mapper.xml部分,大家先有个简单的印象,方便后续文章进行分析。
- CompanyMapper.xml
xml中仅有一个select查询语句,为了便于分析${}
与#{}
两种占位符的差别,我在一个语句中分别使用了两种不同的方式来设置参数id。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.raysonxin.dao.CompanyDao">
<resultMap id="baseResultMap" type="com.raysonxin.dataobject.CompanyDO">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="cpy_type" property="cpyType"/>
</resultMap>
<select id="selectById" resultMap="baseResultMap">
select id,name,cpy_type from company
<where>
<if test="id != null">
id = ${id} or id = #{id}
</if>
</where>
</select>
</mapper>
- CompanyDao.java
public interface CompanyDao {
/**
* 根据id查询CompanyDO
*
* @param cmpId 主键id
* @return 查询结果
*/
CompanyDO selectById(@Param("id") Integer cmpId);
}
- Program.java
public class Program {
public static void main(String[] args) throws IOException {
// mybatis配置文件
String path = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(path);
// 获取 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 创建 SqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
CompanyDao dao = sqlSession.getMapper(CompanyDao.class);
CompanyDO companyDO = dao.selectById(1);
System.out.println(companyDO);
}
}
}
下图来自之前的文章《Mybatis源码之SQL执行过程》,经过前文的分析,我们知道Mapper接口的方法是通过动态代理的方式由代理类MapperProxy委托到SqlSession对应的接口执行的,MapperProxy#invoke才是Mapper方法的真正入口,而本文所要分析的参数设置过程也是从这里开始的(确切来讲是MapperProxy#invoke方法所调用的MapperMethod#execute方法)。
Mybatis的参数设置流程,与我们常规意义上调用方法的参数设置有些不同。因为我们调用Mapper接口的方法,其参数虽然在接口中有定义,但是实际是作用在SQL语句上,而SQL语句是通过占位符(${}
与#{}
)来预占参数的。
这里其实就可能存在一定的差异,Mapper接口方法所定义的参数名称、个数、类型、顺序等一定与SQL语句的要求匹配吗?如果匹配,那Mybatis是如何把我们给定的参数,按照预期为SQL语句设置参数的呢?带着这几个问题,我们开始Mybatis参数设置流程的分析!
参数解析
由于Mapper接口方法执行时调用的是MapperMethod,其执行依赖MappedStatement中SqlSource对参数的要求。因此,在方法执行之前,Mybatis需要先把Mapper接口参数名称解析为通用的、可被理解的方式;同时,引入一些特性支持开发人员的参数定制。
结合示例代码,我们使用的是select语句,也就是会执行SELECT命令,MapperMethod#execute仅贴出与SELECT有关的代码进行说明。
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
//省略INSERT、UPDATE、DELTE、FLUSH……
//仅查看SELECT命令
case SELECT:
//无返回值或者具有ResultHandler
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
}
//返回列表
else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
}
//返回Map
else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
}
//返回Cursor
else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
}
//返回单个结果
else {
//参数转换:把参数转为sql命令参数
Object param = method.convertArgsToSqlCommandParam(args);
//调用SqlSession#selectOne方法
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional() &&
(result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
在SELECT命令最后一个else的代码块(第27行),调用了MethodSignature#convertArgsToSqlCommandParam方法,作用是把我们通过Mapper接口传入的参数转为SQL命令参数。先通过断点看下方法执行后的效果:
示例中我们给接口selectById传入的参数为id=1(但是参数名id其实是不存在的),经过这个方法的处理,我们得到了一个名为param的ParamMap对象,其中包含两个键值对:id=1,param1=1;接着就把param交给了SqlSession#selectOne方法去执行。先不要着急想为什么这么转换,我们先来了解下转换的过程(我已经贴心的为绘制了这一过程的时序图)。
跟着代码走,我们会一步步走到ParamNameResolver#getNamedParams,在此之前已经在MapperMethod构造方法中完成了ParamNameResolver的实例化,所以我们先看下ParamNameResolver的构造方法,然后再了解getNamedParams的实现过程。(同一个类,代码放在一起了,省略部分无关方法)。
public class ParamNameResolver {
//通用参数名称前缀
private static final String GENERIC_NAME_PREFIX = "param";
/**
* <p>
* The key is the index and the value is the name of the parameter.
* The name is obtained from {@link Param} if specified. When {@link Param} is not specified,
* the parameter index is used. Note that this index could be different from the actual index
* when the method has special parameters (i.e. {@link RowBounds} or {@link ResultHandler}).
* </p>
* <ul>
* <li>aMethod(@Param("M") int a, @Param("N") int b) -> {{0, "M"}, {1, "N"}}</li>
* <li>aMethod(int a, int b) -> {{0, "0"}, {1, "1"}}</li>
* <li>aMethod(int a, RowBounds rb, int b) -> {{0, "0"}, {2, "1"}}</li>
* </ul>
*/
private final SortedMap<Integer, String> names;
private boolean hasParamAnnotation;
public ParamNameResolver(Configuration config, Method method) {
// 获取方法的参数类型,示例中即Integer
final Class<?>[] paramTypes = method.getParameterTypes();
// 获取方法参数的@Param注解列表
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
final SortedMap<Integer, String> map = new TreeMap<>();
int paramCount = paramAnnotations.length;
// get names from @Param annotations
// 从@Param中获取参数名称
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
// 是否为特殊参数,特殊参数是指RowBounds、ResultHandler
if (isSpecialParameter(paramTypes[paramIndex])) {
// skip special parameters
continue;
}
String name = null;
// 按照参数顺序获取注解
for (Annotation annotation : paramAnnotations[paramIndex]) {
//判断是否为@Param注解
if (annotation instanceof Param) {
// 标记具有@Param注解
hasParamAnnotation = true;
// 获取@Param注解中的参数名称,示例中“cmpId”
name = ((Param) annotation).value();
// 获取到注解中的参数即停止
break;
}
}
// 到这里,说明从注解中未获取到参数名称
if (name == null) {
// @Param was not specified.
// 未定指定@Param,允许使用实际参数名称,我们示例中的id
if (config.isUseActualParamName()) {
// 获取方法中实际参数名称
name = getActualParamName(method, paramIndex);
}
// 走到这,就采用参数的索引顺序作为名称,如“0”、“1”。。。
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
// gcode issue #71
name = String.valueOf(map.size());
}
}
// 以参数索引顺序为key、上述过程获取到的名称为value,存储到map
// 示例中:0->id
map.put(paramIndex, name);
}
names = Collections.unmodifiableSortedMap(map);
}
//……
/**
* <p>
* A single non-special parameter is returned without a name.
* Multiple parameters are named using the naming rule.
* In addition to the default names, this method also adds the generic names (param1, param2,
* ...).
* </p>
*/
public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
// args为null,或者paramCount=0,返回null
if (args == null || paramCount == 0) {
return null;
}
// 无@Param注解并且只有一个参数,直接返回args的第一个元素
else if (!hasParamAnnotation && paramCount == 1) {
return args[names.firstKey()];
}
// 使用@Param注解或有多个参数
else {
final Map<String, Object> param = new ParamMap<>();
int i = 0;
// 遍历names
for (Map.Entry<Integer, String> entry : names.entrySet()) {
// 以names的value为key,以args值为value,添加到param
param.put(entry.getValue(), args[entry.getKey()]);
// add generic param names (param1, param2, ...)
// 添加通用参数,如param1、param2.。。
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// ensure not to overwrite parameter named with @Param
// 防止重复,覆盖已有参数
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
}
ParamNameResolver构造方法完成了参数名称的获取,其中会跳过特殊类型参数,如RowBounds、ResultHandler,最终以k-v方式存储至SortedMap。参数名称获取过程遵循的优先级规则是:
- 首先,获取@Param注解中设置的参数名称,如示例中的id;
- 其次,使用接口方法定义中的参数名称,如示例中的cmpId;
- 最后,使用参数索引编号作为名称,如“0”、“1”……
getNamedParams方法是为了构造参数名称与参数值的映射关系,**首先****把构造方法中获取到的参数名称与参数值存储到map中,然后为增加通用参数名称与参数值的关系。**这样,在接口方法签名中或@Param注解中的参数名称不与通用参数发生冲突的情况下,每个参数值都会对应两个key,即上面调试截图的形式。
虽然占用的篇幅较多,但是参数解析的过程还是比较简单的,Mybatis结合全局配置,通过反射技术、@Param注解等方式,把接口入参转为一个Map结构,下一步调用SqlSession相关接口完成执行。
动态SQL转为静态SQL【可选】
这里的动态SQL是指DynamicSqlSource,静态SQL是指StaticSqlSource。我对这两者的理解是:
- DynamicSqlSource:SQL语句存在动态元素,需要在运行时通过参数值才能将其转换为结构确定的、可以直接赋值的SQL语句,也就是静态化的SQL;
- StaticSqlSource:包含形如
select * from tb_test where id=?
这样的SQL以及参数映射列表,只需要把其中的?
替换为指定参数即可执行。
通过《Mybatis源码之MappedStatement》这篇文章,我们可以知道,如果在SQL语句中使用了动态元素(如:if标签、${}占位符等)MappedStatement#SqlSource类型为DynamicSqlSource,否则为RawSqlSource。其中,RawSqlSource内部其实封装了一个StaticSqlSource,已经完成了静态化处理及SQL语句中参数的提取操作。示例中,我们的SQL语句使用where、if这类标签,显然是动态SQL。所以,我们接下来按照动态SQL的流程来分析。
主体流程
“参数解析”一节,代码调用到了SqlSession#selectOne方法,随着代码执行,我们可以走到一个关键的方法MappedStatement#getBoundSql,它用来获取一个BoundSql对象。先看一下这段代码的执行逻辑:
public BoundSql getBoundSql(Object parameterObject) {
// 通过SqlSource获取BoundSql对象
BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
// 获取BoundSql中的参数映射列表
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
//如果parameterMappings为空,则使用xml中的参数映射配置。
if (parameterMappings == null || parameterMappings.isEmpty()) {
boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
}
// 一般用不到,省略了
return boundSql;
}
getBoundSql就是为了获取BoundSql对象,首先通过SqlSource获取,如果未获取到parameterMappings,则考虑使用Configuration(即xml配置文件)中的ParameterMap作为参数映射。我们主要分析通过SqlSource获取的过程:示例中是动态SQL,所以这里的sqlSource是DynamicSqlSource的实例。
public class DynamicSqlSource implements SqlSource {
private final Configuration configuration;
private final SqlNode rootSqlNode;
public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) {
this.configuration = configuration;
this.rootSqlNode = rootSqlNode;
}
//org.apache.ibatis.scripting.xmltags.DynamicSqlSource#getBoundSql
public BoundSql getBoundSql(Object parameterObject) {
// 创建动态上下文对象,它里面主要是我们的从第一节获取到的参数解析结果
DynamicContext context = new DynamicContext(configuration, parameterObject);
// 动态SQL内部的SqlNode是MixedSqlNode实例,由多种不同的SqlNode组成,apply会依次调用SqlNode的apply方法
rootSqlNode.apply(context);
SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
// 动态sql的转换过程就在这里。
SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
// 创建BoundSql对象
BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
for (Map.Entry<String, Object> entry : context.getBindings().entrySet()) {
boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
}
return boundSql;
}
}
- DynamicContext对象存储了这个阶段所需要的参数信息、提供了解析后sql语句拼接的工具方法及并存储处理后的sql语句,它贯穿SqlSource解析的整个过程。
- rootSqlNode是MixedSqlNode的实例,它内存通过contents字段存储了SQL语句所包含的SqlNode列表,通过apply方法依次调用各个SqlNode#apply方法,完成SqlNode中表达式的计算及结果输出。例如:通过计算表达式的结果,决定标签内的SQL是否满足执行条件。由于SqlNode的类型有多种,处理方式也不尽相同,具体类型需要具体分析。
- SqlSourceBuilder顾名思义,就是用来做SqlSource构建的工具类,具体来说是StaticSqlSource的构建类。正是通过它完成了从动态到静态的处理过程,期间会提取出SQL语句中通过
#{}
占位符预设的参数映射信息。
DynamicSqlSource#getBoundSql方法的执行过程就比较清晰了,整体分为两个步骤:根据输入参数把MixedSqlNode中各个子SqlNode静态化,然后解析SQL语句中的#{}
占位符所定义的参数映射信息并以?
替换,创建StaticSqlSource对象和BoundSql。先通过下图概括这个阶段的执行过程,其中黄色注释部分是需要具体展开的。
MixedSqlNode#apply
MixedSqlNode代码如下所示,contents存储SQL所包含的所有SqlNode,apply方法执行时,会依次把MixedSqlNode#contents中的SqlNode遍历并调用apply方法。
// MixedSqlNode
public class MixedSqlNode implements SqlNode {
private final List<SqlNode> contents;
public MixedSqlNode(List<SqlNode> contents) {
this.contents = contents;
}
@Override
public boolean apply(DynamicContext context) {
for (SqlNode sqlNode : contents) {
sqlNode.apply(context);
}
return true;
}
}
示例中的contents如下图所示,有两个StaticTextSqlNode、一个IfSqlNode(它内部存储的也是一个MixedSqlNode,包含一个TextSqlNode)。
MixedSqlNode#apply方法的分析过程就比较容易理解,只需要依次看下StaticTextSqlNode、IfSqlNode、TextSqlNode对apply方法的实现过程即可。
- StaticTextSqlNode:静态文本,没有动态元素和参数处理,仅仅是拼接sql语句;
//org.apache.ibatis.scripting.xmltags.StaticTextSqlNode#apply
public boolean apply(DynamicContext context) {
context.appendSql(text);
return true;
}
// org.apache.ibatis.scripting.xmltags.DynamicContext#appendSql
public void appendSql(String sql) {
sqlBuilder.append(sql);
sqlBuilder.append(" ");
}
- IfSqlNode:涉及ONGL表达式的判断,当表达式成立时,再调用IfSqlNode中的SqlNode#apply方法。
//org.apache.ibatis.scripting.xmltags.IfSqlNode#apply
public boolean apply(DynamicContext context) {
//表达式成立继续执行。
if (evaluator.evaluateBoolean(test, context.getBindings())) {
contents.apply(context);
return true;
}
return false;
}
- 此时,SqlNode的类型是MixedSqlNode,跟上面的逻辑类似,所以会执行到TextSqlNode。
**
**TextSqlNode#apply****虽然代码只有两行,**这个过程比较复杂一些,涉及到了占位符${}
的解析过程,我们重点看下。代码如下:
// org.apache.ibatis.scripting.xmltags.TextSqlNode#apply
public boolean apply(DynamicContext context) {
// 创建${}占位符的解析器,其中GenericTokenParser是通用的,BindingTokenParser是对占位符的替换方式实现
GenericTokenParser parser = createParser(new BindingTokenParser(context, injectionFilter));
//解析${},完成替换,把解析结果拼接到sql语句中
context.appendSql(parser.parse(text));
return true;
}
private GenericTokenParser createParser(TokenHandler handler) {
//创建GenericTokenParser,处理的目标是`${`和`}`开闭包含的内容
return new GenericTokenParser("${", "}", handler);
}
GenericTokenParser是一个通用的SQL语句占位符的解析类,会从头到尾依次匹配openToken(如:${
、#{
)和closeToken(如:}
)中间包含的表达式。若匹配到表达式,就会通过TokenHandler接口对象,对匹配表达式进行处理。通过上述代码可以,当处理${}
时使用的是BindingTokenParser。
示例中,GenericTokenParser#parse方法的入参text是(如上图TextSqlNode的内容):
id = ${id} or id = #{id}
GenericTokenParser的parse方法比较长,但是很简单,我们重点来看下当匹配到表达式的处理流程,即BindingTokenParser#handleToken方法:
private static class BindingTokenParser implements TokenHandler {
// 上下文对象,内容包含了参数及sql语句解析结果
private DynamicContext context;
private Pattern injectionFilter;
public BindingTokenParser(DynamicContext context, Pattern injectionFilter) {
this.context = context;
this.injectionFilter = injectionFilter;
}
@Override
// 入参content是GenericTokenParser匹配到的表达式,示例中为“id”
public String handleToken(String content) {
// 获取输入的参数对象。示例为ParamMap,包含:"id"->1,"param1"->1
Object parameter = context.getBindings().get("_parameter");
if (parameter == null) {
context.getBindings().put("value", null);
} else if (SimpleTypeRegistry.isSimpleType(parameter.getClass())) {
context.getBindings().put("value", parameter);
}
//通过ongl获取表达式对应的值,这里获取的value=1。
Object value = OgnlCache.getValue(content, context.getBindings());
String srtValue = value == null ? "" : String.valueOf(value); // issue #274 return "" instead of "null"
//sql入侵检测
checkInjection(srtValue);
return srtValue;
}
private void checkInjection(String value) {
if (injectionFilter != null && !injectionFilter.matcher(value).matches()) {
throw new ScriptingException("Invalid input. Please conform to regex" + injectionFilter.pattern());
}
}
}
代码走下来,我们知道BindingTokenParser#handleToken方法是完成了对GenericTokenParser#parse匹配到表达式的替换,即:由id
替换为参数对应的值1。所以,原来SQL语句前后变化如下:
# GenericTokenParser#parse入参
id = ${id} or id = #{id}
# GenericTokenParser#parse输出结果
id = 1 or id = #{id}
以上处理结果会保存在DynamicContext中,MixedSqlNode#apply也就执行完成了。MixedSqlNode#contents中的SqlNode列表也被处理为了一条比较简洁的SQL语句,如下:
select id,name,cpy_type from company WHERE id = 1 or id = #{id}
SqlSourceBuilder#parse
刚刚有说到,SqlSourceBuilder#parse的作用是匹配SQL语句中的#{}
占位符,并将匹配到的表达式解析为参数映射列表。我们通过代码了解下过程:
//org.apache.ibatis.builder.SqlSourceBuilder#parse
public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
String sql = parser.parse(originalSql);
return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
}
相信大家一眼就看出来了,SqlSourceBuilder#parse的处理过程与TextSqlNode#apply的过程如出一辙,区别就在于SqlSourceBuilder#parse处理的是#{}
,而且使用了ParameterMappingTokenHandler这个TokenHandler实现类。所以,我们只需要了解ParameterMappingTokenHandler#handleToken处理过程即可:
public String handleToken(String content) {
parameterMappings.add(buildParameterMapping(content));
return "?";
}
handleToken通过buildParameterMapping方法创建了ParameterMapping(参数映射)并添加到parameterMappings参数映射列表中;同时返回了?
用于替换原来GenericTokenParser匹配到的表达式。也就是我们常说的,#{}
内的参数会被?
替换。
buildParameterMapping方法比较长,也比较复杂,我现在也没有完全理解,其中的case也没有遇到过,等以后理解了再来补充。虽然未完全理解,但不影响我们对整个过程的把握。在我们的例子中,它会使用构造器ParameterMapping.Builder把表达式转为ParameterMapping,其中会寻找参数映射所需的TypeHandler,用于后续的参数处理。
动态SQL转为静态SQL这个过程就分析完了,其实主要就是两件事:一是ONGL通过输入参数把SqlNode中的SQL片段转为静态的SQL,二是解析处理SQL语句中的参数占位符${}
和#{}
,Mybatis对二者的处理有很大的不同。对于${}
直接将表达式替换为对应的参数值,对于#{}
提取参数信息转为ParameterMapping,并将原来的表示是替换为?
。
预编译参数赋值
终于来到最后一个环节!获得BoundSql之后,回到Mybatis对SQL的执行流程,就会从CachingExecutor一直走到PreparedStatementHandler#parameterize方法,它会使用DefaultParameterHandler对预编译SQL执行参数赋值,它是ParameterHandler的默认实现。当方法运行到这里后,DefaultParameterHandler的关键字段情况如下图所示:
结合上图中boundSql等字段的信息,我们看下setParameters方法的执行流程:
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
// 通过BoundSql获取参数映射列表
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
// 仅参数映射列表非空时处理
if (parameterMappings != null) {
// 遍历参数映射列表
for (int i = 0; i < parameterMappings.size(); i++) {
// 获取当前参数映射
ParameterMapping parameterMapping = parameterMappings.get(i);
// 仅参数类型不是OUT时处理,示例为IN
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
// 获取参数名称
String propertyName = parameterMapping.getProperty();
// 额外参数是否包含当前属性,当前是_parameter和_databaseId
if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
}
// 类型处理器是否包含参数类型,当前参数类型为ParamMap
else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
// 创建MetaObject对象
MetaObject metaObject = configuration.newMetaObject(parameterObject);
// 获取属性对应的值
value = metaObject.getValue(propertyName);
}
// 获取参数映射的类型处理器。这里是UnknownTypeHandler
TypeHandler typeHandler = parameterMapping.getTypeHandler();
// 获取jdbcType
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
//通过类型处理器为ps参数赋值
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
} catch (SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
setParameters方法的执行过程比较清晰:依次遍历参数映射列表,从parameterObject中获取参数对应的值,然后通过类型处理器为PreparedStatement指定索引位置的参数赋值,最终完成所有参数的赋值操作。
这里需要注意的是,在通过TypeHandler为PreparedStatement赋值时,Mybatis会通过类型处理器注册中心查找与当前参数匹配的TypeHandler。因为我们的ParameterMapping是通过对SQL语句中预编译占位符#{}
的解析而得到的,这里并没有明确参数的确切类型,Mybatis为ParameterMapping默认了UnknownTypeHandler作为处理器,即把参数类型默认为Object。所以,在我们的示例中会首先通过UnknownTypeHandler,然后通过resolveTypeHandler找到正确的类型处理器IntegerTypeHandler为PreparedStatement完成赋值操作。
总结
Mybatis参数设置过程到这里就完成了,非常感谢你能耐心的读到这里!简单做个总结吧:Mybatis的参数设置过程其实不仅仅是参数设置那么简单,它涉及了Mybatis对入参的转换处理,MappedStatement对参数的要求,而且对不同的占位符采取了不同的处理方式,以满足我们多种情景的要求;最终通过DefaultParameterHandler完成了对预编译声明PreparedStatement的参数赋值。
我们的示例是比较简单的,仅仅包含了一个参数,而且未涉及这种复杂的标签,你也可以打开源码去了解下。
本文到这里就结束了,希望对您有用,如果觉得有用就点个赞吧,^_^!本人水平有限,如您发现有任何错误或不当之处,欢迎批评指正。也可以关注我的微信公众号:“兮一昂吧”。
公众号搜索“码路印记”,点关注不迷路!