TypeHandler使用手册
场景:想保存user时 teacher自动转String ,不想每次保存都要手动去转String;从DB查询出来时,也要自动帮我们转换成Java对象 Teacher
@Data
public class User {private Integer id;private String name;private Integer sex;//这里直接使用数据库无法识别的自定义类型private Teacher teacher;
}
当然Mybatis给我们提供了接口 TypeHandler
(类型映射)
public interface TypeHandler<T> {//参数转换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;
}
看看mybatis内置的类型处理器,这就是为什么一些Java的数据类型不用我们手动转换的原因
我们可以参考String,看他是怎么处理的,发现都是通过原生的jdbc来处理的
public class StringTypeHandler extends BaseTypeHandler<String> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)throws SQLException {ps.setString(i, parameter);}@Overridepublic String getNullableResult(ResultSet rs, String columnName)throws SQLException {return rs.getString(columnName);}@Overridepublic String getNullableResult(ResultSet rs, int columnIndex)throws SQLException {return rs.getString(columnIndex);}@Overridepublic String getNullableResult(CallableStatement cs, int columnIndex)throws SQLException {return cs.getString(columnIndex);}
}
实战
我们结合springboot来看,启动容器
server:port: 8080
mybatis:mapper-locations: classpath:mappers/*.xmltype-handlers-package: com.example.ssm.demos.web.typeHandler
创建SqlSessionFactory的时候扫描并注册
public class SqlSessionFactoryBean implements InitializingBean {@Overridepublic void afterPropertiesSet() throws Exception {this.sqlSessionFactory = buildSqlSessionFactory();}protected SqlSessionFactory buildSqlSessionFactory() throws Exception {if (hasLength(this.typeHandlersPackage)) {//在包路径下找到实现TypeHandler的类并注册scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers())).forEach(targetConfiguration.getTypeHandlerRegistry()::register);}}
}
注册并加入缓存
public final class TypeHandlerRegistry {private final Map<Type, Map<JdbcType, TypeHandler<?>>> typeHandlerMap = new ConcurrentHashMap<>();private final Map<Class<?>, TypeHandler<?>> allTypeHandlersMap = new HashMap<>();public void register(Class<?> typeHandlerClass) {boolean mappedTypeFound = false;//如果这个类有注解@MappedTypes,根据注解的指定的类进行有参构造实例化MappedTypes mappedTypes = typeHandlerClass.getAnnotation(MappedTypes.class);if (mappedTypes != null) {for (Class<?> javaTypeClass : mappedTypes.value()) {register(javaTypeClass, typeHandlerClass);mappedTypeFound = true;}}//没有注解,直接无参构造实例化if (!mappedTypeFound) {register(getInstance(null, typeHandlerClass));}}//加入缓存 private void register(Type javaType, JdbcType jdbcType, TypeHandler<?> handler) {if (javaType != null) {Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.get(javaType);if (map == null || map == NULL_TYPE_HANDLER_MAP) {map = new HashMap<>();}map.put(jdbcType, handler);typeHandlerMap.put(javaType, map);}allTypeHandlersMap.put(handler.getClass(), handler);}
}
容器启动完成,测试一下
@Mapper
public interface UserMapper {public User getUserListByEntity(Integer id);public int insertUser(User user);
}
定义一个Teacher 处理器
public class TeacherTypeHandler extends BaseTypeHandler<Teacher> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Teacher parameter, JdbcType jdbcType) throws SQLException {ps.setString(i, JSON.toJSONString(parameter));}@Overridepublic Teacher getNullableResult(ResultSet rs, String columnName) throws SQLException {return JSON.parseObject(rs.getString(columnName),Teacher.class);}@Overridepublic Teacher getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return JSON.parseObject(rs.getString(columnIndex),Teacher.class);}@Overridepublic Teacher getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {return JSON.parseObject(cs.getString(columnIndex),Teacher.class);}
}
mapper文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.ssm.demos.web.mapper.UserMapper"><sql id="allUserCollun">id,name,sex,teacher</sql><resultMap id="userMap" type="com.example.ssm.demos.web.pojo.User"><id column="id" property="id"></id><result property="name" column="name"></result><result property="sex" column="sex"></result><!-- 指定字段处理器,反序列化成Teacher对象 --><result property="teacher" column="teacher" typeHandler="com.example.ssm.demos.web.typeHandler.TeacherTypeHandler" ></result></resultMap><!-- 测试查询 --><select id="getUserListByEntity" resultMap="userMap">select<include refid="allUserCollun"></include>from User<where>id = #{id}</where></select><!-- 测试新增 --><insert id="insertUser" parameterType="com.example.ssm.demos.web.pojo.User">insert into user(<include refid="allUserCollun"></include>) values (#{id},#{name},#{sex},<!-- 指定字段处理器,转换成json格式的字符串 -->#{teacher,typeHandler=com.example.ssm.demos.web.typeHandler.TeacherTypeHandler})</insert>
</mapper>
经过测试,完全没有问题,插入数据库时,自动转 String
,查询时,自动转 Teacher
如果想知道调用位置,参数可以看这个类: org.apache.ibatis.scripting.defaults.DefaultParameterHandler#setParameters
返回值可以看这个类: org.apache.ibatis.executor.resultset.DefaultResultSetHandler#getPropertyMappingValue