0%

mybatis之ParameterHandler

ParameterHandler参数处理

ParameterHandler是参数处理器,mybatis通过ParameterHandler对预编译中参数进行设置,如果有配置typeHandler,自然会对注册的typeHandler对参数进行处理

1
2
3
4
5
6
public interface ParameterHandler {
// 获取参数对象
Object getParameterObject();
// 负责调用PreparedStatement.set*方法为SQL绑定实参
void setParameters(PreparedStatement var1) throws SQLException;
}

DefaultParameterHandler

mybatis只为ParameterHandler提供了一个唯一的实现类DefaultParameterHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class DefaultParameterHandler implements ParameterHandler {
// 管理mybatis中全部的TypeHandler对象
private final TypeHandlerRegistry typeHandlerRegistry;
// 记录SQL节点相应的配置信息
private final MappedStatement mappedStatement;
// 用户传入的实参对象
private final Object parameterObject;
// 记录对应参数的名称和相关属性
private final BoundSql boundSql;
private final Configuration configuration;

public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
this.mappedStatement = mappedStatement;
this.configuration = mappedStatement.getConfiguration();
this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
this.parameterObject = parameterObject;
this.boundSql = boundSql;
}

public Object getParameterObject() {
return this.parameterObject;
}

public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(this.mappedStatement.getParameterMap().getId());
// 取除sql中的参数列表
List<ParameterMapping> parameterMappings = this.boundSql.getParameterMappings();
if (parameterMappings != null) {
for(int i = 0; i < parameterMappings.size(); ++i) {
// 获取对应索引位的参数
ParameterMapping parameterMapping = (ParameterMapping)parameterMappings.get(i);
// 过滤存储过程的输出参数
if (parameterMapping.getMode() != ParameterMode.OUT) {
// 获取参数名称
String propertyName = parameterMapping.getProperty();
Object value;
// 获取对应实参值
if (this.boundSql.hasAdditionalParameter(propertyName)) {
value = this.boundSql.getAdditionalParameter(propertyName);
} else if (this.parameterObject == null) {
value = null;
} else if (this.typeHandlerRegistry.hasTypeHandler(this.parameterObject.getClass())) {
value = this.parameterObject;
} else {
MetaObject metaObject = this.configuration.newMetaObject(this.parameterObject);
value = metaObject.getValue(propertyName);
}

TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = this.configuration.getJdbcTypeForNull();
}

try {
// 该方法会调用PreparedStatement.set*方法为SQL语句绑定相应的实参
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (SQLException | TypeException var10) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + var10, var10);
}
}
}
}

}
}

欢迎关注我的其它发布渠道