MyBatis 提供了很多默认类型处理器,参考官网地址:链接,除了官网提供的类型处理器,我们也可以自定义类型处理器。

具体做法为:实现 org.apache.ibatis.type.TypeHandler 接口, 或继承 org.apache.ibatis.type.BaseTypeHandler 类 , 然后可以选择性地将它映射到一个 JDBC 类型。

测试类:com.yjw.demo.TypeHandlerTest

比如我们要自定义一个性别的枚举类型处理器,实现步骤如下所示:

创建类型处理器

定义性别的枚举

  1. /**
  2. * 性格枚举
  3. *
  4. * @author yinjianwei
  5. * @date 2018/09/27
  6. */
  7. public enum Sex {
  8. MALE(1, "男"), FEMALE(2, "女");
  9. private Integer code;
  10. private String value;
  11. private Sex(Integer code, String value) {
  12. this.code = code;
  13. this.value = value;
  14. }
  15. /**
  16. * 根据code获得value
  17. *
  18. * @param code
  19. * @return
  20. */
  21. public static String getValue(Integer code) {
  22. String value = null;
  23. for (Sex sex : Sex.values()) {
  24. if (sex.getCode().equals(code)) {
  25. value = sex.getValue();
  26. }
  27. }
  28. return value;
  29. }
  30. /**
  31. * 根据code获取sex
  32. *
  33. * @param code
  34. * @return
  35. */
  36. public static Sex getSex(Integer code) {
  37. for (Sex sex : Sex.values()) {
  38. if (sex.getCode().equals(code)) {
  39. return sex;
  40. }
  41. }
  42. return null;
  43. }
  44. /**
  45. * @return the code
  46. */
  47. public Integer getCode() {
  48. return code;
  49. }
  50. /**
  51. * @param code the code to set
  52. */
  53. public void setCode(Integer code) {
  54. this.code = code;
  55. }
  56. /**
  57. * @return the value
  58. */
  59. public String getValue() {
  60. return value;
  61. }
  62. /**
  63. * @param value the value to set
  64. */
  65. public void setValue(String value) {
  66. this.value = value;
  67. }
  68. }

创建性别类型处理器 SexEnumTypeHandler

  1. /**
  2. * 性别类型处理器
  3. *
  4. * @author yinjianwei
  5. * @date 2018/09/27
  6. */
  7. public class SexEnumTypeHandler extends BaseTypeHandler<Sex> {
  8.  
  9. /**
  10. * 入参处理
  11. */
  12. @Override
  13. public void setNonNullParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
  14. ps.setInt(i, parameter.getCode());
  15. }
  16.  
  17. /**
  18. * 返回结果处理
  19. */
  20. @Override
  21. public Sex getNullableResult(ResultSet rs, String columnName) throws SQLException {
  22. int code = rs.getInt(columnName);
  23. if (rs.wasNull()) {
  24. return null;
  25. } else {
  26. return Sex.getSex(code);
  27. }
  28. }
  29.  
  30. /**
  31. * 返回结果处理
  32. */
  33. @Override
  34. public Sex getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
  35. int code = rs.getInt(columnIndex);
  36. if (rs.wasNull()) {
  37. return null;
  38. } else {
  39. return Sex.getSex(code);
  40. }
  41. }
  42.  
  43. /**
  44. * 存储过程返回结果(CallableStatement)处理
  45. */
  46. @Override
  47. public Sex getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  48. int code = cs.getInt(columnIndex);
  49. if (cs.wasNull()) {
  50. return null;
  51. } else {
  52. return Sex.getSex(code);
  53. }
  54. }
  55.  
  56. }

这里使用的是继承 org.apache.ibatis.type.BaseTypeHandler 类的方式,重写父类的四个方法,分别对入参和返回结果做了类型转换处理。

配置类型处理器

有两种方式配置类型处理器,一种是在 MyBatis 的配置文件中配置,可以实现类型处理器的自动发现;另外一种是显式地为那些 SQL 语句设置要使用的类型处理器。

MyBatis 配置文件中配置

application-dev.yml

  1. mybatis:
  2. type-aliases-package: com.yjw.demo.mybatis.biz.pojo.entity;com.yjw.demo.mybatis.biz.pojo.query
  3. mapper-locations: classpath:mapper/*.xml
  4. configLocation: classpath:mybatis-config.xml
  5. # configuration:
  6. # lazy-loading-enabled: true
  7. # aggressive-lazy-loading: false

mybatis.configLocation:指定 MyBatis 的 XML 配置文件路径。

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <typeHandlers>
  6. <typeHandler javaType="com.yjw.demo.mybatis.common.constant.Sex"
  7. jdbcType="TINYINT"
  8. handler="com.yjw.demo.mybatis.common.type.SexEnumTypeHandler"/>
  9. </typeHandlers>
  10. </configuration>

mybatis-config.xml 文件配置 typeHandler,通过显示的指定 javaType 和 jdbcType 实现类型处理器的自动发现,比如在调用如下 insert 配置的时候就不需要显示的指定 typeHandler,就可以实现类型转换的功能。

StudentMapper.xml

  1. <insert id="insert" parameterType="studentDO" keyProperty="id" useGeneratedKeys="true">
  2. insert into t_student (name, sex, selfcard_no, note)
  3. values (
  4. #{name,jdbcType=VARCHAR},
  5. #{sex,jdbcType=TINYINT},
  6. #{selfcardNo,jdbcType=BIGINT},
  7. #{note,jdbcType=VARCHAR}
  8. )
  9. </insert>

显示指定类型处理器

如果在 mybatis-config.xml 配置文件中没有配置 typeHandler,可以在各个映射文件中显示配置需要使用的类型处理器,也可以实现类型转换的功能。

比如在调用如下 insert 配置的时候显示的指定 typeHandler。

StudentMapper.xml

  1. <insert id="insert" parameterType="studentDO" keyProperty="id" useGeneratedKeys="true">
  2. insert into t_student (name, sex, selfcard_no, note)
  3. values (
  4. #{name,jdbcType=VARCHAR},
  5. #{sex,jdbcType=TINYINT,typeHandler=com.yjw.demo.mybatis.common.type.SexEnumTypeHandler},
  6. #{selfcardNo,jdbcType=BIGINT},
  7. #{note,jdbcType=VARCHAR}
  8. )
  9. </insert>

上面的例子只展现了入参的类型转换的效果,返回结果的效果参考 com.yjw.demo.mybatis.biz.dao.StudentDao#listByConditions 方法,typeHandler 的配置如下。

  1. <resultMap id="BaseResultMap" type="studentDO">
  2. <id column="id" jdbcType="BIGINT" property="id" />
  3. <result column="name" jdbcType="VARCHAR" property="name" />
  4. <result column="sex" jdbcType="TINYINT" property="sex" />
  5. <!--<result column="sex" jdbcType="TINYINT" property="sex"
  6. typeHandler="com.yjw.demo.mybatis.common.type.SexEnumTypeHandler"/>-->
  7. <result column="selfcard_no" jdbcType="BIGINT" property="selfcardNo" />
  8. <result column="note" jdbcType="VARCHAR" property="note" />
  9. </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. 2018年蓝桥杯java b组第八题

    标题:日志统计 小明维护着一个程序员论坛.现在他收集了一份"点赞"日志,日志共有N行.其中每一行的格式是: ts id 表示在ts时刻编号id的帖子收到一个"赞" ...

  2. 7.Sentinel源码分析—Sentinel是怎么和控制台通信的?

    这里会介绍: Sentinel会使用多线程的方式实现一个类Reactor的IO模型 Sentinel会使用心跳检测来观察控制台是否正常 Sentinel源码解析系列: 1.Sentinel源码分析-F ...

  3. electron教程(三): 使用ffi-napi引入C++的dll

    我的electron教程系列 electron教程(一): electron的安装和项目的创建 electron教程(二): http服务器, ws服务器, 进程管理 electron教程(三): 使 ...

  4. SpringBoot集成Spring Security入门体验

    一.前言 Spring Security 和 Apache Shiro 都是安全框架,为Java应用程序提供身份认证和授权. 二者区别 Spring Security:重量级安全框架 Apache S ...

  5. Java 8 时间日期使用

    一.日期时间 Java 8通过发布新的Date-Time API (JSR 310)来进一步加强对日期与时间的处理.java.util.Date和SimpleDateFormatter都不是线程安全的 ...

  6. Flask基础(15)-->模板代码的复用【宏(Macro)、继承(Block)、包含(include)】

    宏 对宏(macro)的理解: 把它看作 Jinja2 中的一个函数,它会返回一个模板或者 HTML 字符串 为了避免反复地编写同样的模板代码,出现代码冗余,可以把他们写成函数以进行重用 需要在多处重 ...

  7. Thinkphp5.0终章

    thinkphp5.0最终总结 前期刚开始我是跟着b站上的千峰教育的视频走的,一路上做笔记进行深化与实际操作,中间因为不会开报错,并且视频里面也没有讲到怎么弄报错,因为是新手,那种出错了却不知道错在哪 ...

  8. 配置中心-Apollo

    配置中心-Apollo 2019/10/01 Chenxin 配置服务主要有 携程Apollo.百度Disconf.阿里ACM,目前以Apollo用户量最大.适用场景,多用于微服务,与K8S结合好. ...

  9. C语言-查找一个元素在数组中的位置

    #include<stdio.h> #include <stdlib.h> #include <time.h> int search(int key, int a[ ...

  10. drf框架安装配置及其功能概述

    0902自我总结 drf框架安装配置及其功能概述 一.安装 pip3 install djangorestframework 二.配置 # 注册drf app NSTALLED_APPS = [ # ...