MyBatis虽然有很好的SQL执行性能,但毕竟不是完整的ORM框架,不同的数据库之间SQL执行还是有差异。 笔者最近在升级 Oracle 驱动至 ojdbc 7 ,就发现了处理DATE类型存在问题。还好MyBatis提供了使用自定义TypeHandler转换类型的功能。
本文介绍如下使用 TypeHandler 实现日期类型的转换。
问题背景
项目中有如下的字段,是采用的DATE类型:
birthday = #{birthday, jdbcType=DATE},
在更新 Oracle 驱动之前,DateOnlyTypeHandler会做出处理,将 jdbcType 是 DATE 的数据转为短日期格式(‘年月日’)插入数据库。毕竟是生日嘛,只需要精确到年月日即可。
但是,升级 Oracle 驱动至 ojdbc 7 ,就发现了处理DATE类型存在问题。插入的数据格式变成了长日期格式(‘年月日时分秒’),显然不符合需求了。
解决方案:
MyBatis提供了使用自定义TypeHandler转换类型的功能。可以自己写个TypeHandler来对 DATE 类型做特殊处理:
1/** 2 * Welcome to https://waylau.com 3 */ 4package com.waylau.lite.mall.type; 5 6import java.sql.CallableStatement; 7import java.sql.PreparedStatement; 8import java.sql.ResultSet; 9import java.sql.SQLException; 10import java.text.DateFormat; 11import java.util.Date; 12 13import org.apache.ibatis.type.BaseTypeHandler; 14import org.apache.ibatis.type.JdbcType; 15import org.apache.ibatis.type.MappedJdbcTypes; 16import org.apache.ibatis.type.MappedTypes; 17 18/** 19 * 自定义TypeHandler,用于将日期转为'yyyy-MM-dd' 20 * 21 * @since 1.0.0 2018年10月10日 22 * @author <a href="https://waylau.com">Way Lau</a> 23 */ 24@MappedJdbcTypes(JdbcType.DATE) 25@MappedTypes(Date.class) 26public class DateShortTypeHandler extends BaseTypeHandler<Date> { 27 28 @Override 29 public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) 30 throws SQLException { 31 DateFormat df = DateFormat.getDateInstance(); 32 String dateStr = df.format(parameter); 33 ps.setDate(i, java.sql.Date.valueOf(dateStr)); 34 } 35 36 @Override 37 public Date getNullableResult(ResultSet rs, String columnName) throws SQLException { 38 java.sql.Date sqlDate = rs.getDate(columnName); 39 if (sqlDate != null) { 40 return new Date(sqlDate.getTime()); 41 } 42 return null; 43 } 44 45 @Override 46 public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException { 47 java.sql.Date sqlDate = rs.getDate(columnIndex); 48 if (sqlDate != null) { 49 return new Date(sqlDate.getTime()); 50 } 51 return null; 52 } 53 54 @Override 55 public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { 56 java.sql.Date sqlDate = cs.getDate(columnIndex); 57 if (sqlDate != null) { 58 return new Date(sqlDate.getTime()); 59 } 60 return null; 61 } 62 63}
如果是 Spring 项目,以下面方式进行 TypeHandler 的配置:
1<!-- 自定义 --> 2<!--声明TypeHandler bean--> 3<bean id="dateShortTypeHandler" class="com.waylau.lite.mall.type.DateShortTypeHandler"/> 4 5<!-- MyBatis 工厂 --> 6<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 7 <property name="dataSource" ref="dataSource" /> 8 9 <!--TypeHandler注入--> 10 <property name="typeHandlers" ref="dateShortTypeHandler"/> 11</bean>
如何使用 TypeHandler
方式1 :指定 jdbcType 为 DATE
比如,目前,项目中有如下的字段,是采用的DATE类型:
birthday = #{birthday, jdbcType=DATE},
方式2 :指定 typeHandler
指定 typeHandler 为我们自定义的 TypeHandler:
birthday = #{birthday, typeHandler=com.waylau.lite.mall.type.DateShortTypeHandler},
源码
见https://github.com/waylau/lite-book-mall