Mybatis 文档篇 2.4:Configuration 之 TypeHandlers

1 Configuration Structure

2 TypeHandlers

2.1 默认的 TypeHandler

Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a value from a ResultSet, a TypeHandler is used to retrieve the value in a means appropriate to the Java type.
作用:无论是 Mybatis 在 PreparedStatement 设置参数还是从 ResultSet 获取值,TypeHandler 都会将获取到的值以一个合适的方式转换成 Java 类型。

默认的 TypeHandler 对应表

2.2 自定义 TypeHandler

You can override the type handlers or create your own to deal with unsupported or non-standard types.
你可以重写类型处理器或者创建你自己的类型处理器来处理不支持的或者非标准的类型。

To do so, implement the interface org.apache.ibatis.type.TypeHandler or extend the convenience class org.apache.ibatis.type.BaseTypeHandler and optionally map it to a JDBC type.
具体方法是:实现接口 org.apache.ibatis.type.TypeHandler 或者继承类 org.apache.ibatis.type.BaseTypeHandler ,选择性地将它映射到 JDBC 类型。

// ExampleTypeHandler.java
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ExampleTypeHandler extends BaseTypeHandler<String> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, parameter);
  }

  @Override
  public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return rs.getString(columnName);
  }

  @Override
  public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return rs.getString(columnIndex);
  }

  @Override
  public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return cs.getString(columnIndex);
  }

}
<!-- mybatis-config.xml -->
<typeHandlers>
  <typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
</typeHandlers>

Using such a TypeHandler would override the existing type handler for Java String properties and VARCHAR parameters and results.
使用这样一个 TypeHandler 将覆盖已经存在的处理 Java String 类型属性和 VARCHAR 参数和结果集的类型处理器。

2.3 MyBatis 如何查找 TypeHandler

Note that MyBatis does not introspect upon the database metadata to determine the type, so you must specify that it’s a VARCHAR field in the parameter and result mappings to hook in the correct type handler.
注意,MyBatis 不会窥探数据库元信息来决定使用哪种类型,所以你必须在参数和结果集中指定这是个 VARCHAR 类型的字段,从而可以使用正确的类型处理器。

This is due to the fact that MyBatis is unaware of the data type until the statement is executed.
这是因为 MyBatis 直到语句执行才知道数据类型。

2.3.1 如何知道 Java Type

MyBatis will know the Java type that you want to handle with this TypeHandler by introspecting its generic type, but you can override this behavior by two means:
MyBatis 会通过查看泛型来知道你想要通过该 TypeHandler 处理的 Java 类型,你也可以通过以下两种方式覆盖这个行为:

  • Adding a javaType attribute to the typeHandler element (for example: javaType="String")
    在 mybatis-config.xml 中的 typeHandler 元素中添加 javaType 属性。(例如:javaType="String")

  • Adding a @MappedTypes annotation to your TypeHandler class specifying the list of java types to associate it with. This annotation will be ignored if the javaType attribute as also been specified.
    在 TypeHandler 类中通过加入 @MappedTypes 注解的方式指定关联的 Java 类型列表。如果已经设置了 javaType 属性,这个注解将被忽略。
    如:@MappedTypes({Integer.class, Double.class})

2.3.2 如何知道 JDBC Type

Associated JDBC type can be specified by two means:
有以下两种方式可指定 JDBC 类型:

  • Adding a jdbcType attribute to the typeHandler element (for example: jdbcType="VARCHAR").
    在 typeHandler 元素中添加 jdbcType 属性。(例如:jdbcType="VARCHAR")

  • Adding a @MappedJdbcTypes annotation to your TypeHandler class specifying the list of JDBC types to associate it with. This annotation will be ignored if the jdbcType attribute as also been specified.
    在你的 TypeHandler 类中添加 @MappedJdbcTypes 注解指定要关联的 JDBC 类型列表。如果已经设置了 jdbcType 属性,这个注解将被忽略。
    如:@MappedJdbcTypes({JdbcType.INTEGER, JdbcType.DOUBLE})

2.3.3 如何选择 TypeHandler

When deciding which TypeHandler to use in a ResultMap, the Java type is known (from the result type), but the JDBC type is unknown.
当决定在 ResultMap 中使用哪个 TypeHandler 时,Java 类型是已知的(从结果类型中知道),但 JDBC 类型是未知的。

MyBatis therefore uses the combination javaType=[TheJavaType], jdbcType=null to choose a TypeHandler.
因此,MyBatis 使用 javaType=[TheJavaType], jdbcType=null 的组合去选择一个 TypeHandler。

This means that using a @MappedJdbcTypes annotation restricts the scope of a TypeHandler and makes it unavailable for use in ResultMaps unless explicity set.
这就意味着使用 @MappedJdbcTypes 注解可以限制 TypeHandler 的范围,除非显式设置,否则 TypeHandler 在 ResultMap 中是无效的。

To make a TypeHandler available for use in a ResultMap, set includeNullJdbcType=true on the @MappedJdbcTypes annotation.
为了使 TypeHandler 在 ResultMap 中有效,在 @MappedJdbcTypes 注解上设置 includeNullJdbcType=true 即可。

Since Mybatis 3.4.0 however, if a single TypeHandler is registered to handle a Java type, it will be used by default in ResultMaps using this Java type (i.e. even without includeNullJdbcType=true).
但是从 Mybatis 3.4.0 开始,如果单个 TypeHandler 只被注册绑定给一个 Java 类型,它将在使用该 Java 类型的 ResultMap 中被默认使用。不用设置 includeNullJdbcType=true)

And finally you can let MyBatis search for your TypeHandlers:
最后你可以让 MyBatis 来查找你的 TypeHandler:

<!-- mybatis-config.xml -->
<typeHandlers>
  <package name="org.mybatis.example"/>
</typeHandlers>

Note that when using the autodiscovery feature JDBC types can only be specified with annotations.
注意,当使用自动检索功能时,JDBC 类型仅能通过注解方式被指定。

2.4 创建可以处理多个类的 TypeHandler

You can create a generic TypeHandler that is able to handle more than one class.
作用:你可以创建一个可以处理多个类的泛型类型处理器。

For that purpose add a constructor that receives the class as a parameter and MyBatis will pass the actual class when constructing the TypeHandler.
怎么做:为了使用泛型类型处理器,需要增加一个接收该类的 class 作为参数的构造器,Mybatis 会在构造该 TypeHandler 时传递一个具体的类。

//GenericTypeHandler.java
public class GenericTypeHandler<E extends MyObject> extends BaseTypeHandler<E> {
  private Class<E> type;
  public GenericTypeHandler(Class<E> type) {
    if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
    this.type = type;
  }
  ...
}

EnumTypeHandler and EnumOrdinalTypeHandler are generic TypeHandlers.
EnumTypeHandler 和 EnumOrdinalTypeHandler 就是泛型类型构造器。

2.5 Handling Enums

If you want to map an Enum, you'll need to use either EnumTypeHandler or EnumOrdinalTypeHandler.For example, let's say that we need to store the rounding mode that should be used with some number if it needs to be rounded.
使用场景:如果你想要映射一个枚举类型,你将会用到 EnumTypeHandler 或 EnumOrdinalTypeHandler。比如,我们想使用 RoundingMode 来存取数字的近似值(java.math.RoundingMode 是一个 Enum)。

By default, MyBatis uses EnumTypeHandler to convert the Enum values to their names.
默认情况下,MyBatis 使用 EnumTypeHandler 转换枚举值到对应的名字。

Note EnumTypeHandler is special in the sense that unlike other handlers, it does not handle just one specific class, but any class that extends Enum.
注意,在某种意义上,相比于其他的处理器,EnumTypeHandler 是特殊的,它不止能处理某个特定的类,而是能处理所有继承自 Enum 的类。

However, we may not want to store names. Our DBA may insist on an integer code instead. That's just as easy: add EnumOrdinalTypeHandler to the typeHandlers in your config file, and now each RoundingMode will be mapped to an integer using its ordinal value.
但是,我们可能不想要存储名字。我们的 DBA 可能坚持要使用整型值来替代它。那也一样简单:给配置文件中的 typeHandlers 添加 EnumOrdinalTypeHandler 即可,这样每个 RoundingMode 将通过它们的序数值映射成对应的数值。

<!-- mybatis-config.xml -->
<typeHandlers>
  <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="java.math.RoundingMode"/>
</typeHandlers>

But what if you want to map the same Enum to a string in one place and to integer in another?
但是万一你想要将同样的 Enum 同时映射成字符串类型和整型呢?

The auto-mapper will automatically use EnumOrdinalTypeHandler, so if we want to go back to using plain old ordinary EnumTypeHandler, we have to tell it, by explicitly setting the type handler to use for those SQL statements.
自动映射器会自动使用 EnumOrdinalTypeHandler,所以如果我们想使用普通的 EnumTypeHandler,我们就需要在语句中显式地定义该类型处理器。

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.apache.ibatis.submitted.rounding.Mapper">
        <resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <result column="funkyNumber" property="funkyNumber"/>
                <result column="roundingMode" property="roundingMode"/>
        </resultMap>

        <select id="getUser" resultMap="usermap">
                select * from users
        </select>

        <insert id="insert">
            insert into users (id, name, funkyNumber, roundingMode) values (
                #{id}, #{name}, #{funkyNumber}, #{roundingMode}
            )
        </insert>
        
        <resultMap type="org.apache.ibatis.submitted.rounding.User" id="usermap2">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <result column="funkyNumber" property="funkyNumber"/>
                <result column="roundingMode" property="roundingMode" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
        </resultMap>

        <select id="getUser2" resultMap="usermap2">
                select * from users2
        </select>

        <insert id="insert2">
            insert into users2 (id, name, funkyNumber, roundingMode) values (
                #{id}, #{name}, #{funkyNumber}, #{roundingMode, typeHandler=org.apache.ibatis.type.EnumTypeHandler}
            )
        </insert>
</mapper>

最后

说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!

当前版本:mybatis-3.5.0
官网文档:MyBatis
官网翻译:MyBatis 简体中文
项目实践:MyBatis Learn

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267