使用?mybatis?自定義日期類型轉(zhuǎn)換器的示例代碼
前言
使用mybatis中的typeHandlers 實(shí)現(xiàn)自定義日期類型的轉(zhuǎn)換器。
重點(diǎn)在2.2 handler中
一、resources

1.1 sqlMapConfig.xml
typeHandlers: 自定義的日期類型轉(zhuǎn)換器:
(1)將日期類型轉(zhuǎn)為long的長整型存入數(shù)據(jù)庫中。
(2)將數(shù)據(jù)庫中的bigint(本質(zhì)對應(yīng)java的long類型)轉(zhuǎn)為date類型。environments:加載數(shù)據(jù)庫mapper: 映射文件的位置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeHandlers>
<typeHandler handler="com.mytest.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com.mytest.mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>1.2 log4j.properties
打印日志
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout1.3 userMapper.xml
1.findByid: 通過id查詢插入元素
2.save: xml映射器mapper時(shí),
useGeneratedKeys:值為true 并分別指定屬性:
keyProperty: 對應(yīng)的Java對象的主鍵屬性
keyColumn: 對應(yīng)的數(shù)據(jù)庫記錄主鍵字段
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mytest.dao.UserMapper">
<!-- 通過id查詢插入元素-->
<select id="findByid" parameterType="int" resultType="com.mytest.pojo.User">
select * from sys_user where id=#{id}
</select>
<!-- 插入元素-->
<insert id="save" parameterType="com.mytest.pojo.User" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into sys_user(id,username,email,password,phoneNum,birthday) values(null,#{username},null,#{password},null,#{birthday})
</insert>
</mapper>
二、java結(jié)構(gòu)

2.1 dao
UserMapper
1.findByid: 使用id值查詢User
2.save: 插入U(xiǎn)ser到數(shù)據(jù)庫中
package com.mytest.dao;
import com.mytest.pojo.User;
import java.util.List;
public interface UserMapper {
User findByid(int id);
public void save(User user);
}2.2 handler
DateTypeHandler
- setNonNullParameter:將java類型 轉(zhuǎn)換成 數(shù)據(jù)庫需要的類型
- getNullableResult:將數(shù)據(jù)庫中類型 轉(zhuǎn)換成java類型
package com.mytest.handler;
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;
public class DateTypeHandler extends BaseTypeHandler<Date> {
//將java類型 轉(zhuǎn)換成 數(shù)據(jù)庫需要的類型
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i,time);
}
//將數(shù)據(jù)庫中類型 轉(zhuǎn)換成java類型
//String參數(shù) 要轉(zhuǎn)換的字段名稱
//ResultSet 查詢出的結(jié)果集
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
//獲得結(jié)果集中需要的數(shù)據(jù)(long) 轉(zhuǎn)換成Date類型 返回
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
}2.3 pojo
package com.mytest.pojo;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String password;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
public Integer getId() {
return id;
public void setId(Integer id) {
this.id = id;
public String getUsername() {
return username;
public void setUsername(String username) {
this.username = username;
public String getPassword() {
return password;
public void setPassword(String password) {
this.password = password;
}2.4 service
service沒用進(jìn)行實(shí)現(xiàn),在本demo中只用于測試使用。
sqlSession.commit()用于mybatis的事務(wù)提交。mybatis的事務(wù)默認(rèn)是不提交的,故在增刪改中需要進(jìn)行事務(wù)的提交,在mybatis中事務(wù)的提交方式一般有兩種:
1 sqlSession.commit()
2 采用openSession(true),即可實(shí)現(xiàn)自動(dòng)提交,無需調(diào)用commit()方法。
package com.mytest.service;
import com.mytest.dao.UserMapper;
import com.mytest.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class ServiceTest {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) new SqlSessionFactoryBuilder().build(inputStream);
//openSession為true則自動(dòng)提交事務(wù)
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
//插入不需要設(shè)置id值
// user.setId(5);
user.setUsername("wangwu");
user.setPassword("123");
user.setBirthday(new Date());
//會返回屬性值
mapper.save(user);
Integer userId = user.getId();
sqlSession.commit();
User findUser = mapper.findByid(userId);
System.out.println(findUser);
}
}三 數(shù)據(jù)表結(jié)構(gòu)及測試
數(shù)據(jù)表結(jié)構(gòu)

測試

到此這篇關(guān)于使用 mybatis 自定義日期類型轉(zhuǎn)換器的文章就介紹到這了,更多相關(guān)mybatis 自定義日期類型轉(zhuǎn)換器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MybatisPlus字段類型轉(zhuǎn)換的實(shí)現(xiàn)示例
- mybatis自定義參數(shù)類型轉(zhuǎn)換器數(shù)據(jù)庫字段加密脫敏
- mybatis-plus?分頁類型轉(zhuǎn)換工具類
- mybatis類型轉(zhuǎn)換器如何實(shí)現(xiàn)數(shù)據(jù)加解密
- Mybatis自定義類型轉(zhuǎn)換器的使用技巧
- MyBatis自定義類型轉(zhuǎn)換器實(shí)現(xiàn)加解密
- Mybatis實(shí)現(xiàn)自定義類型轉(zhuǎn)換器TypeHandler的方法
- MyBatis類型轉(zhuǎn)換模塊的實(shí)現(xiàn)
相關(guān)文章
使用@RequestParam設(shè)置默認(rèn)可以傳空值
這篇文章主要介紹了使用@RequestParam設(shè)置默認(rèn)可以傳空值的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
MyBatis學(xué)習(xí)教程(四)-如何快速解決字段名與實(shí)體類屬性名不相同的沖突問題
我們經(jīng)常會遇到表中的字段名和表對應(yīng)實(shí)體類的屬性名稱不一定都是完全相同的情況,如何解決呢?下面腳本之家小編給大家介紹MyBatis學(xué)習(xí)教程(四)-如何快速解決字段名與實(shí)體類屬性名不相同的沖突問題,一起學(xué)習(xí)吧2016-05-05
修改request的parameter的幾種方式總結(jié)
這篇文章主要介紹了修改request的parameter的幾種方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Spring Boot 配置MySQL數(shù)據(jù)庫重連的操作方法
這篇文章主要介紹了Spring Boot 配置MySQL數(shù)據(jù)庫重連的操作方法,需要的朋友可以參考下2018-04-04
詳解maven的setting配置文件中mirror和repository的區(qū)別
這篇文章主要介紹了詳解maven的setting配置文件中mirror和repository的區(qū)別,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12
在logback.xml中自定義動(dòng)態(tài)屬性的方法
這篇文章主要介紹了在logback.xml中自定義動(dòng)態(tài)屬性的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08

