Mybatis之typeHandler类型转换器

在JDBC中,需要通过PreparedStatement对象中设置那些已经预编译过的SQL语句的参数,执行SQL后,会通过ResultSet对象获取得到数据库的数据,而这些MyBatis是根据数据的类型通过typeHandler来实现的,在typeHandler中,分为jdbcType和javaType,其中jdbcType用于定义数据库类型,而javaType用于定义java类型,那么typeHandler的作用就是承担jdbcType和javaType之间的相互转换,
在很多中情况下,我们并不需要去配置typeHandler,jdbctype,javatype。因为MyBatis会探测应该使用什么类型的typeHandler进行配置,但是有些场景就无法探测到,对于那些需要使用自定义的枚举的场景,或者数据库使用特殊数据类型的场景,可以使用自定义的typeHandler去处理类型之间的转换问题。

源码分析

在MyBatis中typeHandler都要实现接口org.apache.ibatis.type.TypeHandler,首先让我们先看看这个接口的定义

/**
 * @author Clinton Begin
 */
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;
 
}

这里我们稍微说明一下他们的定义

  • 其中T是泛型,专指javaType,比如我们需要String的时候,那么实现类可以写为implements TypeHandler<String>
  • setParameter方法,是使用typeHandler通过PreparedStatement对象设置SQL参数的时候使用的具体方法,其中i是参数在SQL的下标,parameter是参数,jdbcType是数据库类型
  • 其中有三个getResult的方法,它的作用是从JDBC结果集中获取数据进行转换,要么使用列名,(columnname)要么使用下标(columnIndex)获取数据库的数据,其中最后一个getResult方法是存储过程使用的。
    TypeHandler源码实现
public abstract class BaseTypeHandler<T> extends TypeReference<T> implements TypeHandler<T> {
 
  protected Configuration configuration;
 
  public void setConfiguration(Configuration c) {
    this.configuration = c;
  }
 
  @Override
  public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
    if (parameter == null) {
      if (jdbcType == null) {
        throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
      }
      try {
        ps.setNull(i, jdbcType.TYPE_CODE);
      } catch (SQLException e) {
        throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
                "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
                "Cause: " + e, e);
      }
    } else {
      try {
        setNonNullParameter(ps, i, parameter, jdbcType);
      } catch (Exception e) {
        throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
                "Try setting a different JdbcType for this parameter or a different configuration property. " +
                "Cause: " + e, e);
      }
    }
  }
 
  @Override
  public T getResult(ResultSet rs, String columnName) throws SQLException {
    T result;
    try {
      result = getNullableResult(rs, columnName);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set.  Cause: " + e, e);
    }
    if (rs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }
 
  @Override
  public T getResult(ResultSet rs, int columnIndex) throws SQLException {
    T result;
    try {
      result = getNullableResult(rs, columnIndex);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column #" + columnIndex+ " from result set.  Cause: " + e, e);
    }
    if (rs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }
 
  @Override
  public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
    T result;
    try {
      result = getNullableResult(cs, columnIndex);
    } catch (Exception e) {
      throw new ResultMapException("Error attempting to get column #" + columnIndex+ " from callable statement.  Cause: " + e, e);
    }
    if (cs.wasNull()) {
      return null;
    } else {
      return result;
    }
  }
 
  public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
 
  public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;
 
  public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;
 
  public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;
 
}

简单分析一下BaseTypeHandler的源码

  • BaseTypeHandler是一个抽象类,它实现了TypeHandler的所有接口,需要子类去实现它自定义的4个抽象方法
  • setParameter方法中,当parameter和jdbcType都为空时将抛出异常,如果能明确jdbcType,将会进行空设置(PreparedStatement的setNull方法);如果paramter不为空,将使用setNonNullParameter去设置参数(该方法需要子类去实现)
  • getResult方法,非空结果集是通过getNullableResult方法去获取的,该方法需要子类去实现,同样是针对下标、列名以及存储过程三种的实现
  • getNullableParameter方法用于存储过程

Mybatis使用最多的是typeHandler之一是——StringTypeHandler.它用于字符串转换、

/**
 * @author Clinton Begin
 */
public class StringTypeHandler 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);
  }
}

显然它实现了BaseTypeHandler的4个抽象方法,代码也非常简单。
在这里,MyBatis把javaType和jdbcType相互转换,那么他们是如何进行注册的呢?在MyBatis中采用org.apache.ibatis.type.TypeHandlerRegistry类对象的register方法进行注册

public TypeHandlerRegistry() {
    register(Boolean.class, new BooleanTypeHandler());
    register(boolean.class, new BooleanTypeHandler());
    register(JdbcType.BOOLEAN, new BooleanTypeHandler());
    register(JdbcType.BIT, new BooleanTypeHandler());
}

这样就实现用代码的形式注册typeHandler,注意,自定义的typeHandler一般不会使用代码注册,而是通过配置或者扫描。0

自定义typeHandler

从系统定义的typeHandler可以知道,要实现typeHandler就需要去实现接口typeHandler,或者继承BaseTypeHandler(实际上BassseTypeHandler实现了typehandler的接口)

package com.learn.ssm.chapter4.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.log4j.Logger;

public class MyTypeHandler implements TypeHandler<String> {

    Logger logger=Logger.getLogger(MyTypeHandler.class);
//  这个就是一个日志的对象,记录和这个类对象进行的一切操作,记录用户的操作
    
    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        // TODO Auto-generated method stub
        String result=rs.getString(columnName);
        logger.info("读取string参数1【"+result+"】");
        return result;
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        // TODO Auto-generated method stub
        String result=rs.getString(columnIndex);
        logger.info("读取string参数2【"+result+"】");
        return result;
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        // TODO Auto-generated method stub
        String result=cs.getString(columnIndex);
        logger.info("读取string参数3【"+result+"】");
        return result;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter,
            JdbcType jdbcType) throws SQLException {
        // TODO Auto-generated method stub
        logger.info("设置string参数["+parameter+"]");
        ps.setString(i, parameter);
    }

}

定义的typeHandler泛型为String,显然我们要把数据库的数据类型转换为String型,然后实现设置参数和获取结果集方法
配置typeHandler,配置文件在mybatis-config.xml

<!-- 配置typehandler -->
<typeHandlers>
         <typeHandler jdbcType="VARCHAR" javaType="string" handler="com.learn.ssm.chapter4.typehandler.MyTypeHandler" 
            /> 
<!--        <package name="com.learn.ssm.chapter4.typehandler" /> -->

    </typeHandlers>

配置完成后系统才会读取它,这样注册后,当jdbcType和javaType能与MyTypeHandler对应的时候,它就会启动MyTypeHandler.有时候还可以显示启用typeHandler,一般而言启用这个typeHandler有 两种方式。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learn.ssm.chapter3.mapper.RoleMapper">
<!-- namespace所对应的是一个接口的全限定名,于是MyBatis上下文就可以通过它找到对应的接口  -->
    <resultMap id="roleMapper" type="role">
        <result property="id" column="id" />
        <result property="roleName" column="role_name" jdbcType="VARCHAR"
            javaType="string" />
        <result property="note" column="note"
            typeHandler="com.learn.ssm.chapter4.typehandler.MyTypeHandler" />
    </resultMap>

    <select id="getRole" parameterType="long" resultMap="roleMapper">
        select id, role_name, note from t_role where id = #{id}
    </select>

    <select id="findRoles" parameterType="string" resultMap="roleMapper">
        select id, role_name, note from t_role
        where role_name like concat('%', #{roleName, jdbcType=VARCHAR,
        javaType=string}, '%')
    </select>
<!--第一种:用配置中一样的jdbcType和javaType-->
    <select id="findRoles2" parameterType="string" resultMap="roleMapper">
        select id, role_name, note from t_role
        where note like concat('%', #{note,
        typeHandler=com.learn.ssm.chapter4.typehandler.MyTypeHandler}, '%')
    </select>
    <!--第二种:直接用具体的实现类-->
</mapper>

注意要么指定了与自定义typeHandler一致的jdbcType和javaType,要么直接使用typeHandler指定具体的实现类,在一些因为数据库返回为空导致无法断定采用哪个typeHandler来处理,而又没有注册对应的javaType的typeHandler时,MyBatis无法知道使用哪个typeHandler

  • 补充 resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中
<!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<resultMap id="唯一的标识" type="映射的pojo对象">
  <id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
  <result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
  <association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
    <id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
    <result  column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
  </association>
  <!-- 集合中的property须为oftype定义的pojo对象的属性-->
  <collection property="pojo的集合属性" ofType="集合中的pojo对象">
    <id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
    <result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />  
  </collection>
</resultMap>

运行

package com.learn.ssm.chapter4.main;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.learn.ssm.chapter3.mapper.RoleMapper;

import com.learn.ssm.chapter3.pojo.Role;

import com.learn.ssm.chapter3.utils.SqlSessionFactoryUtils;

public class chapter4Main {

    public static void main(String[] args) {
        testRoleMapper();
//      testTypeHandler();
    }

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

推荐阅读更多精彩内容