From: http://www.manongjc.com/article/15577.htmlhtml
MyBatis雖然有很好的SQL執行性能,但畢竟不是完整的ORM框架,不一樣的數據庫之間SQL執行仍是有差別。 筆者最近在升級 Oracle 驅動至 ojdbc 7 ,就發現了處理DATE類型存在問題。還好MyBatis提供了使用自定義TypeHandler轉換類型的功能。java
本文介紹以下使用 TypeHandler 實現日期類型的轉換。git
問題背景
github
項目中有以下的字段,是採用的DATE類型:spring
birthday = #{birthday, jdbcType=DATE},
在更新 Oracle 驅動以前,DateOnlyTypeHandler會作出處理,將 jdbcType 是 DATE 的數據轉爲短日期格式(‘年月日')插入數據庫。畢竟是生日嘛,只須要精確到年月日便可。sql
可是,升級 Oracle 驅動至 ojdbc 7 ,就發現了處理DATE類型存在問題。插入的數據格式變成了長日期格式(‘年月日時分秒'),顯然不符合需求了。數據庫
解決方案:
apache
MyBatis提供了使用自定義TypeHandler轉換類型的功能。能夠本身寫個TypeHandler來對 DATE 類型作特殊處理:mybatis
/** * 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" rel="external nofollow" >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 的配置:app
<!-- 自定義 --> <!--聲明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
以上就是本文的所有內容,但願對你們的學習有所幫助,也但願你們多多支持腳本之家。