SpringBoot系列 Mybatis 之自定義類型轉換 TypeHandler
在使用 mybatis 進行 db 操作的時候,我們經常會干的一件事情就是將 db 中字段映射到 java bean,通常我們使用ResultMap
來實現映射,通過這個標簽可以指定兩者的綁定關系,那么如果 java bean 中的字段類型與 db 中的不一樣,應該怎么處理呢?
如 db 中為 timestamp, 而 java bean 中定義的卻是 long
- 通過
BaseTypeHandler
來實現自定義的類型轉換
I. 環境准備
1. 數據庫准備
使用 mysql 作為本文的實例數據庫,新增一張表
CREATE TABLE `money` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '用戶名',
`money` int(26) NOT NULL DEFAULT '0' COMMENT '錢',
`is_deleted` tinyint(1) NOT NULL DEFAULT '0',
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
`update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
2. 項目環境
本文借助 SpringBoot 2.2.1.RELEASE
+ maven 3.5.3
+ IDEA
進行開發
pom 依賴如下
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
db 配置信息 application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password:
II. 實例演示
1. entity 定義
注意上面 case 中的create_at
與 update_at
的類型都是timestmap
,我們定義的 Entity 如下
@Data
public class MoneyPo {
private Integer id;
private String name;
private Long money;
private Integer isDeleted;
private Timestamp createAt;
private Long updateAt;
}
2. Mapper 測試接口
定義一個簡單的查詢接口,這里直接使用注解的方式(至於 xml 的寫法差別也不大)
/**
* 主鍵查詢
*
* @param id id
* @return {@link MoneyPo}
*/
@Select("select * from money where id = #{id}")
@Results(id = "moneyResultMap", value = {
@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER),
@Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR),
@Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER),
@Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT),
@Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP),
// @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)})
@Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP, typeHandler = Timestamp2LongHandler.class)})
MoneyPo getById(@Param("id") int id);
// 關於 SelectProvider 的使用,后面再說,主要是動態sql的演示
@SelectProvider(type = MoneyService.class, method = "getByIdSql")
@ResultMap(value = "moneyResultMap")
MoneyPo getByIdForProvider(@Param("id") int id);
說明:
@Results
: 這個注解與 ResultMap 標簽效果一致,主要用於定義 db 的字段與 java bean 的映射關系id = "moneyResultMap"
這個 id 定義,可以實現@Results 的復用@Result
: 關注下updateAt
的 typeHandler,這里指定了自定義的 TypeHandler,來實現JdbcType.TEMSTAMP
與 Java Bean 中的 long 的轉換
3. 類型轉換
自定義類型轉換,主要是繼承BaseTypeHandler
類,泛型的類型為 Java Bean 中的類型
/**
* 自定義類型轉換:將數據庫中的日期類型,轉換成long類型的時間戳
*
* 三種注冊方式:
* 1.直接在 result標簽中,指定typeHandler,如@Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP, typeHandler = Timestamp2LongHandler.class)
* 2.在SqlSessionFactory實例中,注冊 在SqlSessionFactory實例中.setTypeHandlers(new Timestamp2LongHandler());
* 3.xml配置,<typeHandler handler="com.git.hui.boot.mybatis.handler.Timestamp2LongHandler"/>
*
* @author yihui
* @date 2021/7/7
*/
@MappedTypes(value = Long.class)
@MappedJdbcTypes(value = {JdbcType.DATE, JdbcType.TIME, JdbcType.TIMESTAMP})
public class Timestamp2LongHandler extends BaseTypeHandler<Long> {
/**
* 將java類型,轉換為jdbc類型
*
* @param preparedStatement
* @param i
* @param aLong 毫秒時間戳
* @param jdbcType db字段類型
* @throws SQLException
*/
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Long aLong, JdbcType jdbcType) throws SQLException {
if (jdbcType == JdbcType.DATE) {
preparedStatement.setDate(i, new Date(aLong));
} else if (jdbcType == JdbcType.TIME) {
preparedStatement.setTime(i, new Time(aLong));
} else if (jdbcType == JdbcType.TIMESTAMP) {
preparedStatement.setTimestamp(i, new Timestamp(aLong));
}
}
@Override
public Long getNullableResult(ResultSet resultSet, String s) throws SQLException {
return parse2time(resultSet.getObject(s));
}
@Override
public Long getNullableResult(ResultSet resultSet, int i) throws SQLException {
return parse2time(resultSet.getObject(i));
}
@Override
public Long getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return parse2time(callableStatement.getObject(i));
}
private Long parse2time(Object value) {
if (value instanceof Date) {
return ((Date) value).getTime();
} else if (value instanceof Time) {
return ((Time) value).getTime();
} else if (value instanceof Timestamp) {
return ((Timestamp) value).getTime();
}
return null;
}
}
- setNonNullParameter:將 java 類型,轉換為 jdbc 類型
- getNullableResult:將 jdbc 類型轉 java 類型
4. TypeHandler 注冊
我們自己定義一個 TypeHandler 沒啥問題,接下來就是需要它生效,一般來講,有下面幾種方式
4.1 result 標簽中指定
通過 result 標簽中的 typeHandler 指定
使用 xml 的方式如
<result column="update_at" property="updateAt" jdbcType="TIMESTAMP" typeHandler="com.git.hui.boot.mybatis.handler.Timestamp2LongHandler"/>
注解@Result 的方式如
@Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP, typeHandler = Timestamp2LongHandler.class)
4.2 SqlSessionFactory 全局配置
上面的使用姿勢為精確指定,如果我們希望應用到所有的場景,則可以通過SqlSessionFactory
來實現
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(
// 設置mybatis的xml所在位置,這里使用mybatis注解方式,沒有配置xml文件
new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
// 注冊typehandler,供全局使用
bean.setTypeHandlers(new Timestamp2LongHandler());
return bean.getObject();
}
4.3 全局 xml 配置
除上面 case 之外,還有一個就是借助mybatis-config.xml
配置文件來注冊,如
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.1//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 駝峰下划線格式支持 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeHandlers>
<typeHandler handler="com.git.hui.boot.mybatis.handler.Timestamp2LongHandler"/>
</typeHandlers>
</configuration>
注意,使用上面的配置文件,需要在 SpringBoot 中指定如下配置,否則將不會生效
mybatis:
config-location: classpath:mybatis-config.xml
4.4 SpringBoot 配置方式
springboot 配置文件,可以通過指定type-handlers-package
來注冊 TypeHandler
mybatis:
type-handlers-package: com.git.hui.boot.mybatis.handler
5. 小結
本文主要介紹 db 中的類型與 java bean 中類型的映射適配策略,主要是通過繼承BaseTypeHandler
來實現自定義的類型轉化
要使用自定義的 TypeHandler,有全局生效與精確指定兩種方式
@Result
/<result>
標簽中,通過 typeHandler 指定- SqlSessionFactory 全局設置 typeHandler
mybatis-config.xml
配置文件設置typeHandlers
此外本文的配置中,還支持了駝峰與下划線的互轉配置,這個也屬於常見的配置,通過在mybatis-config
中如下配置即可
<setting name="mapUnderscoreToCamelCase" value="true"/>
接下來問題來了,駝峰可以和下划線互轉,那么有辦法實現自定義的 name 映射么,如果有知道的小伙伴,請不吝指教
III. 不能錯過的源碼和相關知識點
0. 項目
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/104-mybatis-ano
- 源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/103-mybatis-xml
mybatis 系列博文
- 【DB 系列】SpringBoot 系列 Mybatis 之 Mapper 接口與 Sql 綁定幾種姿勢
- 【DB 系列】SpringBoot 系列 Mybatis 之 Mapper 注冊的幾種方式
- 【DB 系列】Mybatis-Plus 多數據源配置
- 【DB 系列】Mybatis 基於 AbstractRoutingDataSource 與 AOP 實現多數據源切換
- 【DB 系列】Mybatis 多數據源配置與使用
- 【DB 系列】JdbcTemplate 之多數據源配置與使用
- 【DB 系列】Mybatis-Plus 代碼自動生成
- 【DB 系列】MybatisPlus 整合篇
- 【DB 系列】Mybatis+注解整合篇
- 【DB 系列】Mybatis+xml 整合篇
1. 一灰灰 Blog
盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現 bug 或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛
- 一灰灰 Blog 個人博客 https://blog.hhui.top
- 一灰灰 Blog-Spring 專題博客 http://spring.hhui.top