Mybatis--TypeHandler使用手册

news/2024/4/30 4:21:27

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.cpky.cn/p/11581.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

RP2040开发笔记

RP2040 采用合宙的RP2040(板载4MB Flash)&#xff0c; 所有开发资料参考官方&#xff1a;树莓派 Pico 中文站

阿里云弹性计算通用算力型u1实例性能评测,性价比高

阿里云服务器u1是通用算力型云服务器&#xff0c;CPU采用2.5 GHz主频的Intel(R) Xeon(R) Platinum处理器&#xff0c;ECS通用算力型u1云服务器不适用于游戏和高频交易等需要极致性能的应用场景及对业务性能一致性有强诉求的应用场景(比如业务HA场景主备机需要性能一致)&#xf…

InternLM2-lesson2笔记

书生浦语大模型趣味 Demo 视频连接&#xff1a;https://www.bilibili.com/video/BV1AH4y1H78d/?vd_source902e3124d4683c41b103f1d1322401fa 目录 书生浦语大模型趣味 Demo课程总览SIG项目Demo部署的一般流程存在的问题总结 课程总览 InternLM2-chat-1.8B部署八戒-chat-1.8B…

FastAPI Web框架教程 第1章 快速上手

1.1 fastapi介绍 简介&#xff1a; FastAPI 是一个高性能&#xff0c;易于学习&#xff0c;高效编码&#xff0c;生产可用的Python Web异步框架 FastAPI 适合来写API&#xff0c;使用 Python 3.6 并基于标准的 Python 类型提示 核心特性&#xff1a; 速度快&#xff1a;可…

使用 Kafka 保证消息不丢失的策略及原理解析

✨✨祝屏幕前的小伙伴们每天都有好运相伴左右&#xff0c;一定要天天开心&#xff01;✨✨ &#x1f388;&#x1f388;作者主页&#xff1a; 喔的嘛呀&#x1f388;&#x1f388; 目录 一、引言 二. 持久化存储 2.1持久化存储原理&#xff1a; 2.2使用示例&#xff1a; …

利用Spark将Kafka数据流写入HDFS

利用Spark将Kafka数据流写入HDFS 在当今的大数据时代&#xff0c;实时数据处理和分析变得越来越重要。Apache Kafka作为一个分布式流处理平台&#xff0c;已经成为处理实时数据的事实标准。而Apache Spark则是一个强大的大数据处理框架&#xff0c;它提供了对数据进行复杂处理…