mybatis TypeHandler 类型处理器
生活随笔
收集整理的這篇文章主要介紹了
mybatis TypeHandler 类型处理器
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
- 1. 自定義日期類型處理器
- 2. 配置自定義日期處理器
- 3. 新增,查詢
1. 自定義日期類型處理器
繼承mybatis提供的BaseTypeHandler覆寫(xiě)方法, 來(lái)轉(zhuǎn)換Java和數(shù)據(jù)庫(kù)中的字段 package cn.bitqian.config;import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType;import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date;/*** 日期類型處理器* 將日期類型轉(zhuǎn)換為long/long轉(zhuǎn)換為util.date* 將Util.date 轉(zhuǎn)換為數(shù)據(jù)庫(kù)中的bigint(long)* @author echo lovely* @date 2020/9/11 21:15*/ public class DateTypeHandler extends BaseTypeHandler<Date> {// util.date ==> 插入數(shù)據(jù)庫(kù)中的變?yōu)閎igint類型@Overridepublic void setNonNullParameter(PreparedStatement preparedStatement,int i, Date date, JdbcType jdbcType) throws SQLException {if (date != null) {long time = date.getTime();preparedStatement.setLong(i, time);}}// 下面三個(gè)重載 用于查詢數(shù)據(jù)庫(kù)中的字段,轉(zhuǎn)換為日期@Overridepublic Date getNullableResult(ResultSet resultSet, String s) throws SQLException {System.out.println("obj========" + resultSet.getObject(s));long birthdayTime = resultSet.getLong(s);if (birthdayTime != 0)return new Date(birthdayTime);return null;}@Overridepublic Date getNullableResult(ResultSet resultSet, int i) throws SQLException {long birthdayTime = resultSet.getLong(i);System.out.println(birthdayTime);if (birthdayTime != 0)return new Date(birthdayTime);return null;}@Overridepublic Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {long birthdayTime = callableStatement.getLong(i);if (birthdayTime != 0)return new Date(birthdayTime);return null;} }2. 配置自定義日期處理器
<!-- 指定額、日期類型處理器 --><typeHandlers><typeHandler handler="cn.bitqian.config.DateTypeHandler"/></typeHandlers>3. 新增,查詢
// 測(cè)試新增 日期轉(zhuǎn)換為長(zhǎng)整型@Testpublic void test1() {SqlSession session = getSession();if (session != null) {UserMapper mapper = session.getMapper(UserMapper.class);User user = new User(null, "lucy", "999", new Date());int count = mapper.save(user);System.out.println(count);session.close();}}@Testpublic void test2() {SqlSession session = getSession();if (session != null) {UserMapper mapper = session.getMapper(UserMapper.class);// long int -> util.dateSystem.out.println(mapper.selectUserById(6));session.close();}}log4j debug如下
- 你可能需要?jiǎng)討B(tài)sql
- mapper接口用于curd
總結(jié)
以上是生活随笔為你收集整理的mybatis TypeHandler 类型处理器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: extjs中元数据_Extjs中Stor
- 下一篇: 拦截器(二)