MyBatis 示例-类型处理器
MyBatis 提供了很多默认类型处理器,参考官网地址:链接,除了官网提供的类型处理器,我们也可以自定义类型处理器。
具体做法为:实现 org.apache.ibatis.type.TypeHandler
接口, 或继承 org.apache.ibatis.type.BaseTypeHandler
类 , 然后可以选择性地将它映射到一个 JDBC 类型。
测试类:com.yjw.demo.TypeHandlerTest
比如我们要自定义一个性别的枚举类型处理器,实现步骤如下所示:
创建类型处理器
定义性别的枚举
- /**
- * 性格枚举
- *
- * @author yinjianwei
- * @date 2018/09/27
- */
- public enum Sex {
- MALE(1, "男"), FEMALE(2, "女");
- private Integer code;
- private String value;
- private Sex(Integer code, String value) {
- this.code = code;
- this.value = value;
- }
- /**
- * 根据code获得value
- *
- * @param code
- * @return
- */
- public static String getValue(Integer code) {
- String value = null;
- for (Sex sex : Sex.values()) {
- if (sex.getCode().equals(code)) {
- value = sex.getValue();
- }
- }
- return value;
- }
- /**
- * 根据code获取sex
- *
- * @param code
- * @return
- */
- public static Sex getSex(Integer code) {
- for (Sex sex : Sex.values()) {
- if (sex.getCode().equals(code)) {
- return sex;
- }
- }
- return null;
- }
- /**
- * @return the code
- */
- public Integer getCode() {
- return code;
- }
- /**
- * @param code the code to set
- */
- public void setCode(Integer code) {
- this.code = code;
- }
- /**
- * @return the value
- */
- public String getValue() {
- return value;
- }
- /**
- * @param value the value to set
- */
- public void setValue(String value) {
- this.value = value;
- }
- }
创建性别类型处理器 SexEnumTypeHandler
- /**
- * 性别类型处理器
- *
- * @author yinjianwei
- * @date 2018/09/27
- */
- public class SexEnumTypeHandler extends BaseTypeHandler<Sex> {
- /**
- * 入参处理
- */
- @Override
- public void setNonNullParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
- ps.setInt(i, parameter.getCode());
- }
- /**
- * 返回结果处理
- */
- @Override
- public Sex getNullableResult(ResultSet rs, String columnName) throws SQLException {
- int code = rs.getInt(columnName);
- if (rs.wasNull()) {
- return null;
- } else {
- return Sex.getSex(code);
- }
- }
- /**
- * 返回结果处理
- */
- @Override
- public Sex getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
- int code = rs.getInt(columnIndex);
- if (rs.wasNull()) {
- return null;
- } else {
- return Sex.getSex(code);
- }
- }
- /**
- * 存储过程返回结果(CallableStatement)处理
- */
- @Override
- public Sex getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
- int code = cs.getInt(columnIndex);
- if (cs.wasNull()) {
- return null;
- } else {
- return Sex.getSex(code);
- }
- }
- }
这里使用的是继承 org.apache.ibatis.type.BaseTypeHandler
类的方式,重写父类的四个方法,分别对入参和返回结果做了类型转换处理。
配置类型处理器
有两种方式配置类型处理器,一种是在 MyBatis 的配置文件中配置,可以实现类型处理器的自动发现;另外一种是显式地为那些 SQL 语句设置要使用的类型处理器。
MyBatis 配置文件中配置
application-dev.yml
- mybatis:
- type-aliases-package: com.yjw.demo.mybatis.biz.pojo.entity;com.yjw.demo.mybatis.biz.pojo.query
- mapper-locations: classpath:mapper/*.xml
- configLocation: classpath:mybatis-config.xml
- # configuration:
- # lazy-loading-enabled: true
- # aggressive-lazy-loading: false
mybatis.configLocation:指定 MyBatis 的 XML 配置文件路径。
mybatis-config.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <typeHandlers>
- <typeHandler javaType="com.yjw.demo.mybatis.common.constant.Sex"
- jdbcType="TINYINT"
- handler="com.yjw.demo.mybatis.common.type.SexEnumTypeHandler"/>
- </typeHandlers>
- </configuration>
mybatis-config.xml 文件配置 typeHandler,通过显示的指定 javaType 和 jdbcType 实现类型处理器的自动发现,比如在调用如下 insert 配置的时候就不需要显示的指定 typeHandler,就可以实现类型转换的功能。
StudentMapper.xml
- <insert id="insert" parameterType="studentDO" keyProperty="id" useGeneratedKeys="true">
- insert into t_student (name, sex, selfcard_no, note)
- values (
- #{name,jdbcType=VARCHAR},
- #{sex,jdbcType=TINYINT},
- #{selfcardNo,jdbcType=BIGINT},
- #{note,jdbcType=VARCHAR}
- )
- </insert>
显示指定类型处理器
如果在 mybatis-config.xml 配置文件中没有配置 typeHandler,可以在各个映射文件中显示配置需要使用的类型处理器,也可以实现类型转换的功能。
比如在调用如下 insert 配置的时候显示的指定 typeHandler。
StudentMapper.xml
- <insert id="insert" parameterType="studentDO" keyProperty="id" useGeneratedKeys="true">
- insert into t_student (name, sex, selfcard_no, note)
- values (
- #{name,jdbcType=VARCHAR},
- #{sex,jdbcType=TINYINT,typeHandler=com.yjw.demo.mybatis.common.type.SexEnumTypeHandler},
- #{selfcardNo,jdbcType=BIGINT},
- #{note,jdbcType=VARCHAR}
- )
- </insert>
上面的例子只展现了入参的类型转换的效果,返回结果的效果参考 com.yjw.demo.mybatis.biz.dao.StudentDao#listByConditions 方法,typeHandler 的配置如下。
- <resultMap id="BaseResultMap" type="studentDO">
- <id column="id" jdbcType="BIGINT" property="id" />
- <result column="name" jdbcType="VARCHAR" property="name" />
- <result column="sex" jdbcType="TINYINT" property="sex" />
- <!--<result column="sex" jdbcType="TINYINT" property="sex"
- typeHandler="com.yjw.demo.mybatis.common.type.SexEnumTypeHandler"/>-->
- <result column="selfcard_no" jdbcType="BIGINT" property="selfcardNo" />
- <result column="note" jdbcType="VARCHAR" property="note" />
- </resultMap>
如果在 MyBatis 的配置文件(mybatis-config.xml)中配置了 typeHandler 了,这里就不需要显示的配置了。
MyBatis 实用篇
MyBatis 示例-类型处理器的更多相关文章
- Mybatis的类型处理器
Mybatis在预处理语句(PreparedStatement)中设置一个参数时,会用默认的typeHandler进行处理. 这句话是什么意思呢,当你想用姓名查询一个人的信息时 <select ...
- mybatis枚举类型处理器
1. 定义枚举值的接口 public abstract interface ValuedEnum { int getValue(); } 所有要被mybatis处理的枚举类继承该接口 2. 定义枚举类 ...
- MyBatis 示例-传递多个参数
映射器的主要元素: 本章介绍 select 元素中传递多个参数的处理方式. 测试类:com.yjw.demo.MulParametersTest 使用 Map 传递参数(不建议使用) 使用 MyBat ...
- MyBatis 示例-简介
简介 为了全面熟悉 MyBatis 的使用,整理一个 MyBatis 的例子,案例中包含了映射器.动态 SQL 的使用.本章先介绍项目结构和配置. 项目地址:链接 数据库表的模型关系:链接 项目结构 ...
- MyBatis 示例-联合查询
简介 MyBatis 提供了两种联合查询的方式,一种是嵌套查询,一种是嵌套结果.先说结论:在项目中不建议使用嵌套查询,会出现性能问题,可以使用嵌套结果. 测试类:com.yjw.demo.JointQ ...
- MyBatis 示例-缓存
MyBatis 提供两种类型的缓存,一种是一级缓存,另一种是二级缓存,本章通过例子的形式描述 MyBatis 缓存的使用. 测试类:com.yjw.demo.CacheTest 一级缓存 MyBati ...
- MyBatis 示例-动态 SQL
MyBatis 的动态 SQL 包括以下几种元素: 详细的使用参考官网文档:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html 本章内容简单描述这 ...
- MyBatis 示例-插件
简介 利用 MyBatis Plugin 插件技术实现分页功能. 分页插件实现思路如下: 业务代码在 ThreadLocal 中保存分页信息: MyBatis Interceptor 拦截查询请求,获 ...
- MyBatis 示例-主键回填
测试类:com.yjw.demo.PrimaryKeyTest 自增长列 数据库表的主键为自增长列,在写业务代码的时候,经常需要在表中新增一条数据后,能获得这条数据的主键 ID,MyBatis 提供了 ...
随机推荐
- 2018年蓝桥杯java b组第八题
标题:日志统计 小明维护着一个程序员论坛.现在他收集了一份"点赞"日志,日志共有N行.其中每一行的格式是: ts id 表示在ts时刻编号id的帖子收到一个"赞" ...
- 7.Sentinel源码分析—Sentinel是怎么和控制台通信的?
这里会介绍: Sentinel会使用多线程的方式实现一个类Reactor的IO模型 Sentinel会使用心跳检测来观察控制台是否正常 Sentinel源码解析系列: 1.Sentinel源码分析-F ...
- electron教程(三): 使用ffi-napi引入C++的dll
我的electron教程系列 electron教程(一): electron的安装和项目的创建 electron教程(二): http服务器, ws服务器, 进程管理 electron教程(三): 使 ...
- SpringBoot集成Spring Security入门体验
一.前言 Spring Security 和 Apache Shiro 都是安全框架,为Java应用程序提供身份认证和授权. 二者区别 Spring Security:重量级安全框架 Apache S ...
- Java 8 时间日期使用
一.日期时间 Java 8通过发布新的Date-Time API (JSR 310)来进一步加强对日期与时间的处理.java.util.Date和SimpleDateFormatter都不是线程安全的 ...
- Flask基础(15)-->模板代码的复用【宏(Macro)、继承(Block)、包含(include)】
宏 对宏(macro)的理解: 把它看作 Jinja2 中的一个函数,它会返回一个模板或者 HTML 字符串 为了避免反复地编写同样的模板代码,出现代码冗余,可以把他们写成函数以进行重用 需要在多处重 ...
- Thinkphp5.0终章
thinkphp5.0最终总结 前期刚开始我是跟着b站上的千峰教育的视频走的,一路上做笔记进行深化与实际操作,中间因为不会开报错,并且视频里面也没有讲到怎么弄报错,因为是新手,那种出错了却不知道错在哪 ...
- 配置中心-Apollo
配置中心-Apollo 2019/10/01 Chenxin 配置服务主要有 携程Apollo.百度Disconf.阿里ACM,目前以Apollo用户量最大.适用场景,多用于微服务,与K8S结合好. ...
- C语言-查找一个元素在数组中的位置
#include<stdio.h> #include <stdlib.h> #include <time.h> int search(int key, int a[ ...
- drf框架安装配置及其功能概述
0902自我总结 drf框架安装配置及其功能概述 一.安装 pip3 install djangorestframework 二.配置 # 注册drf app NSTALLED_APPS = [ # ...