这一篇只讲TypeHandler,这个类型转换器是mybatis中比较重要的东西,它是用来处理Java对象字段类型和数据库字段类型对应的一个处理器,相当重要,扩展性也很强1.
首先先看下他的一个基本定义
基本定义
基本结构
public interface TypeHandler<T> {
/**
* 设置参数到PreparedStatement中
*/
void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
/**
* 获取名字获取类型
*/
T getResult(ResultSet rs, String columnName) throws SQLException;
/**
* 根据索引获取类型
*/
T getResult(ResultSet rs, int columnIndex) throws SQLException;
/**
* 根据索引获取类型
*/
T getResult(CallableStatement cs, int columnIndex) throws SQLException;
}
这里使用了一个模板设计模式,看看它的一个子类
public abstract class BaseTypeHandler<T> extends TypeReference<T> implements TypeHandler<T> {
protected Configuration configuration;
public void setConfiguration(Configuration c) {
this.configuration = c;
}
@Override
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
if (jdbcType == null) {
throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
}
try {
ps.setNull(i, jdbcType.TYPE_CODE);
} catch (SQLException e) {
throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
"Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
"Cause: " + e, e);
}
} else {
try {
setNonNullParameter(ps, i, parameter, jdbcType);
} catch (Exception e) {
throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
"Try setting a different JdbcType for this parameter or a different configuration property. " +
"Cause: " + e, e);
}
}
}
@Override
public T getResult(ResultSet rs, String columnName) throws SQLException {
T result;
try {
result = getNullableResult(rs, columnName);
} catch (Exception e) {
throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set. Cause: " + e, e);
}
if (rs.wasNull()) {
return null;
} else {
return result;
}
}
@Override
public T getResult(ResultSet rs, int columnIndex) throws SQLException {
T result;
try {
result = getNullableResult(rs, columnIndex);
} catch (Exception e) {
throw new ResultMapException("Error attempting to get column #" + columnIndex+ " from result set. Cause: " + e, e);
}
if (rs.wasNull()) {
return null;
} else {
return result;
}
}
@Override
public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
T result;
try {
result = getNullableResult(cs, columnIndex);
} catch (Exception e) {
throw new ResultMapException("Error attempting to get column #" + columnIndex+ " from callable statement. Cause: " + e, e);
}
if (cs.wasNull()) {
return null;
} else {
return result;
}
}
public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;
public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;
public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;
}
这个类其实就是统一处理异常了,子类在实现的时候就不需要考虑异常问题了,直接当成正常的来写就行,而且这个类还组合了Configuration对象,子类就可以使用这个对象获取整个运行环境的内容数据
所以我们一般都是继承这个类,可以看个稍微简单点的处理器,String类型我们开发过程中是一定要用的
public class StringTypeHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, parameter);
}
@Override
public String getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return rs.getString(columnName);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return rs.getString(columnIndex);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return cs.getString(columnIndex);
}
}
实现是不是很简单!对吧,这个是一个基本结构
初始加载
Mybatis所有属性的设置都是用通过这个类型转换器进行处理的,那么String,Integer这些他是在哪里加载的呢,可以从TypeHandlerRegistry找到答案
Configuration对象有这么一句代码
protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
一上来就创建了一个TypeHandlerRegistry对象,然后可以看到这个对象的构造器,进行了很多基本的注册
public TypeHandlerRegistry() {
register(Boolean.class, new BooleanTypeHandler());
register(boolean.class, new BooleanTypeHandler());
register(JdbcType.BOOLEAN, new BooleanTypeHandler());
register(JdbcType.BIT, new BooleanTypeHandler());
}
这里就不一个个写了,可以具体看到代码里面去,初始化的时候就注册了很多转换器
这个是一个初始化的位置,也不是很复杂,就是知道一下即可
基本使用
基本使用可以参考官方文档
https://mybatis.org/mybatis-3/zh/configuration.html#typeHandlers
先定义一个类型转换器
// ExampleTypeHandler.java
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ExampleTypeHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter);
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getString(columnName);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getString(columnIndex);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getString(columnIndex);
}
}
然后在mybatis-config.xml配置一下
<!-- mybatis-config.xml -->
<typeHandlers>
<typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
</typeHandlers>
这样就行了,只有handler是必须的,其他两个可以在类上面配置注解MappedJdbcTypes表示处理JdbcType.VARCHAR类型,还有一个注解是@MappedTypes,这是映射Java类型的
配置了注解就是全局的
然后如果你某个字段需要用这种拦截器,也可以单独配置
<resultMap id="s" type="com.zxc.study.test.bean.User">
<result property="name" typeHandler="com.zxc.study.test.typeHandler.ZxcTypeHandler"/>
</resultMap>
这种是单独使用的,所以这也是为什么只需要配置handler这个属性即可,因为有不同的用法
以上就是一个基本使用的配置
源码解析
入口你们还记得吗
org.apache.ibatis.builder.xml.XMLConfigBuilder#typeHandlerElement
在这个方法中进行处理的
private void typeHandlerElement(XNode parent) throws Exception {
if (parent != null) {
//需要子节点处理
for (XNode child : parent.getChildren()) {
//如果是配置包路径,mybatis会自动找到TypeHandler类型的类进行注册
if ("package".equals(child.getName())) {
String typeHandlerPackage = child.getStringAttribute("name");
typeHandlerRegistry.register(typeHandlerPackage);
} else {
String javaTypeName = child.getStringAttribute("javaType");
String jdbcTypeName = child.getStringAttribute("jdbcType");
String handlerTypeName = child.getStringAttribute("handler");
Class<?> javaTypeClass = resolveClass(javaTypeName);
JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
//最重要的就是类型处理器,这里一样可以用到别名机制
Class<?> typeHandlerClass = resolveClass(handlerTypeName);
//下面是根据各种判断进行处理
if (javaTypeClass != null) {
//javaTypeClass不为空但是jdbcType为空
if (jdbcType == null) {
typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
} else {
//三个都不为空
typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
}
} else {
//javaTypeClass和jdbcType都为空
typeHandlerRegistry.register(typeHandlerClass);
}
}
}
}
}
代码逻辑还是挺好理解的,主要是不同的分支做了不一样的事
可以每个都稍微看下,首先先看下javaTypeClass不为空但是jdbcType为空的情况
private <T> void register(Type javaType, TypeHandler<? extends T> typeHandler) {
//获取类上面是否指定了处理每个数据库类型的
MappedJdbcTypes mappedJdbcTypes = typeHandler.getClass().getAnnotation(MappedJdbcTypes.class);
if (mappedJdbcTypes != null) {
//循环注册包含处理的jdbc类型
for (JdbcType handledJdbcType : mappedJdbcTypes.value()) {
register(javaType, handledJdbcType, typeHandler);
}
if (mappedJdbcTypes.includeNullJdbcType()) {
register(javaType, null, typeHandler);
}
} else {
//注册,但是不包含jdbc类型
register(javaType, null, typeHandler);
}
}
MappedJdbcTypes 这个注解就是上面说到的
再看下javaTypeClass和jdbcType都不为空的情况
private void register(Type javaType, JdbcType jdbcType, TypeHandler<?> handler) {
//但是你配置的仍然有可能为空....
if (javaType != null) {
Map<JdbcType, TypeHandler<?>> map = TYPE_HANDLER_MAP.get(javaType);
if (map == null || map == NULL_TYPE_HANDLER_MAP) {
map = new HashMap<JdbcType, TypeHandler<?>>();
TYPE_HANDLER_MAP.put(javaType, map);
}
map.put(jdbcType, handler);
}
//配置了全局的转换器
ALL_TYPE_HANDLERS_MAP.put(handler.getClass(), handler);
}
最好的就不看了,因为其实最终都是存到那几个map里去,到时也是从那个map拿出来用,可以简单看下名字
private final Map<JdbcType, TypeHandler<?>> JDBC_TYPE_HANDLER_MAP = new EnumMap<JdbcType, TypeHandler<?>>(JdbcType.class);
private final Map<Type, Map<JdbcType, TypeHandler<?>>> TYPE_HANDLER_MAP = new ConcurrentHashMap<Type, Map<JdbcType, TypeHandler<?>>>();
private final TypeHandler<Object> UNKNOWN_TYPE_HANDLER = new UnknownTypeHandler(this);
private final Map<Class<?>, TypeHandler<?>> ALL_TYPE_HANDLERS_MAP = new HashMap<Class<?>, TypeHandler<?>>();
private static final Map<JdbcType, TypeHandler<?>> NULL_TYPE_HANDLER_MAP = Collections.emptyMap();
private Class<? extends TypeHandler> defaultEnumTypeHandler = EnumTypeHandler.class;
这篇就到此为止,后面使用的时候在执行过程中才会使用到,到时再细说是怎么使用的
写的可能真的一般,不过就当个练习,毕竟也是第一次写这些....