MyBatis使用自定義TypeHandler轉換型別
阿新 • • 發佈:2018-11-10
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 型別做特殊處理:
/**
* Welcome to https://waylau.com
*/
package com.waylau.lite.mall.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
/**
* 自定義TypeHandler,用於將日期轉為'yyyy-MM-dd'
*
* @since 1.0.0 2018年10月10日
* @author <a href="https://waylau.com">Way Lau</a>
*/
@MappedJdbcTypes(JdbcType.DATE)
@MappedTypes(Date.class)
public class DateShortTypeHandler extends BaseTypeHandler<Date> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType)
throws SQLException {
DateFormat df = DateFormat.getDateInstance();
String dateStr = df.format(parameter);
ps.setDate(i, java.sql.Date.valueOf(dateStr));
}
@Override
public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
java.sql.Date sqlDate = rs.getDate(columnName);
if (sqlDate != null) {
return new Date(sqlDate.getTime());
}
return null;
}
@Override
public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
java.sql.Date sqlDate = rs.getDate(columnIndex);
if (sqlDate != null) {
return new Date(sqlDate.getTime());
}
return null;
}
@Override
public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
java.sql.Date sqlDate = cs.getDate(columnIndex);
if (sqlDate != null) {
return new Date(sqlDate.getTime());
}
return null;
}
}
如果是 Spring 專案,以下面方式進行 TypeHandler 的配置:
<!-- 自定義 -->
<!--宣告TypeHandler bean-->
<bean id="dateShortTypeHandler" class="com.waylau.lite.mall.type.DateShortTypeHandler"/>
<!-- MyBatis 工廠 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--TypeHandler注入-->
<property name="typeHandlers" ref="dateShortTypeHandler"/>
</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