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