Spring整合MyBatis后引入自定义类型转化器TypeHandler

MyBatis预定义了许多类型转化器,并不一定能满足所有的需求,如笔者遇到这么个问题:数据库字段类型为datetime时间戳类型,项目组规定ResultMap映射实体时间必须是String类型,MyBatis自带的StringTypeHandler类型转化器转化后的时间字符串会有.0这个小尾巴,像这样2017-03-09 19:00:19.0,然后被测试MM提了BUG。常规的解决方式改下实体的get方法,截掉这个小尾巴就行了,但是笔者觉得不够优雅,决定用自定义类型处理器解决,具体步骤如下

1.编写自定义类型处理器

实现org.apache.ibatis.type.TypeHandler接口或者继承org.apache.ibatis.type.BaseTypeHandler基类,代码片段:

package com.xxx.handler;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

/**
 * Created by Jack.wu on 2017/3/23.
 */
@MappedTypes(String.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class ExtStringTypeHandler 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 {
        Timestamp timestamp = rs.getTimestamp(columnName);
        return DateFormatUtils.format(timestamp.getTime(),"yyyy-MM-dd HH:mm:ss");
    }

    @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);
    }
}

注解@MappedJdbcTypes关联JDBC类型,@MappedTypes注解关联java类型

2.Spring配置TypeHandler

SessionFactory注入typeHandler(dataSource等其他配置省略)

...
<bean id="typeHandler" class="com.xxx.handler.ExtStringTypeHandler" />

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
	<property name="mapperLocations" value="classpath*:mybatis/xxx/*Mapper.xml"/>
	<property name="typeHandlers" ref="typeHandler"/>
</bean>
...

3.ResultMap指定jdbc类型

<resultMap id="BaseResultMap" type="com.xxx.domain.xxx" >
    ...
    <result column="createTime" property="createTime" jdbcType="TIMESTAMP" />
    ...
</resultMap>

也可以在resultMap中直接指定typeHandler,不建议这么做,resultMap一多,得写一堆重复代码

<resultMap id="BaseResultMap" type="com.xxx.domain.xxx" >
    ...
    <result column="createTime" property="createTime" jdbcType="TIMESTAMP" typeHandler="com.xxx.handler.ExtStringTypeHandler"/>
    ...
</resultMap>

参考 http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值