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 示例-类型处理器

MyBatis 示例-传递多个参数

MyBatis 示例-主键回填

MyBatis 示例-动态 SQL

MyBatis 示例-联合查询

MyBatis 示例-缓存

MyBatis 示例-插件

MyBatis 示例-类型处理器的更多相关文章

  1. Mybatis的类型处理器

    Mybatis在预处理语句(PreparedStatement)中设置一个参数时,会用默认的typeHandler进行处理. 这句话是什么意思呢,当你想用姓名查询一个人的信息时 <select ...

  2. mybatis枚举类型处理器

    1. 定义枚举值的接口 public abstract interface ValuedEnum { int getValue(); } 所有要被mybatis处理的枚举类继承该接口 2. 定义枚举类 ...

  3. MyBatis 示例-传递多个参数

    映射器的主要元素: 本章介绍 select 元素中传递多个参数的处理方式. 测试类:com.yjw.demo.MulParametersTest 使用 Map 传递参数(不建议使用) 使用 MyBat ...

  4. MyBatis 示例-简介

    简介 为了全面熟悉 MyBatis 的使用,整理一个 MyBatis 的例子,案例中包含了映射器.动态 SQL 的使用.本章先介绍项目结构和配置. 项目地址:链接 数据库表的模型关系:链接 项目结构 ...

  5. MyBatis 示例-联合查询

    简介 MyBatis 提供了两种联合查询的方式,一种是嵌套查询,一种是嵌套结果.先说结论:在项目中不建议使用嵌套查询,会出现性能问题,可以使用嵌套结果. 测试类:com.yjw.demo.JointQ ...

  6. MyBatis 示例-缓存

    MyBatis 提供两种类型的缓存,一种是一级缓存,另一种是二级缓存,本章通过例子的形式描述 MyBatis 缓存的使用. 测试类:com.yjw.demo.CacheTest 一级缓存 MyBati ...

  7. MyBatis 示例-动态 SQL

    MyBatis 的动态 SQL 包括以下几种元素: 详细的使用参考官网文档:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html 本章内容简单描述这 ...

  8. MyBatis 示例-插件

    简介 利用 MyBatis Plugin 插件技术实现分页功能. 分页插件实现思路如下: 业务代码在 ThreadLocal 中保存分页信息: MyBatis Interceptor 拦截查询请求,获 ...

  9. MyBatis 示例-主键回填

    测试类:com.yjw.demo.PrimaryKeyTest 自增长列 数据库表的主键为自增长列,在写业务代码的时候,经常需要在表中新增一条数据后,能获得这条数据的主键 ID,MyBatis 提供了 ...

随机推荐

  1. Android静态注册广播无法接收的问题(8.0+版本)

    如果你静态注册的广播无法接收到消息,请先检查下:你的安卓版本是不是8.0+ * 前言** Google官方声明:Beginning with Android 8.0 (API level 26), t ...

  2. [Leetcode] 第357题 计算各个位数不同的数字个数

    一.题目描述 给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n . 示例: 输入: 2 输出: 91 解释: 答案应为除去 11,22,33,44,55, ...

  3. (七十六)c#Winform自定义控件-表单验证组件

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  4. 利用Python进行数据分析:【IPython】

    一.IPython基础功能 1.IPython是交互式的Python命令行2.安装与使用 #安装:pip install ipython #使用:ipython与Python解释器的使用方法一致 注: ...

  5. Airtest之web自动化(一)

    Airtest之web自动化(一) [此文档有许多涉及到gif动图的地方,请全屏观看]   了解Airtest: 简介: Airtest是由网易团队开发的一款自动化框架,前期运用与游戏测试(通过截图识 ...

  6. 基于Coravel定时任务之物联网设备数量统计

    目录 基于Coravel定时任务之物联网设备数量统计 1 应用背景 2 对比各家定时库 2.1 TaskScheduler 2.2 Fluent Scheduler 2.3 Quartz.net 2. ...

  7. Excel VBA入门(十)用户窗体开发

    VBA 中的用户窗体就是指带 UI 的用户界面,在运行的时候会单独弹出一个窗口,类似于在 windows 系统中运行的一个可执行程序一样(这个说法不太严谨,因为可执行程序也可能是只有命令窗口而没有 U ...

  8. 『王霸之路』从0.1到2.0一文看尽TensorFlow奋斗史

    ​ 0 序篇 2015年11月,Google正式发布了Tensorflow的白皮书并开源TensorFlow 0.1 版本. 2017年02月,Tensorflow正式发布了1.0.0版本,同时也标志 ...

  9. Spring Cloud Gateway 使用

    简介 Spring Cloud Gateway是Spring Cloud官方推出的网关框架,网关作为流量入口,在微服务系统中有着十分重要的作用,常用功能包括:鉴权.路由转发.熔断.限流等. Sprin ...

  10. Thread线程类

    设置线程名 查看线程名是很简单的,调用Thread.currentThread().getName()即可. public class MyThreadDemo { public static voi ...