使用 mybatis 自定義日期類型轉換器的示例代碼
前言
使用mybatis中的typeHandlers 實現自定義日期類型的轉換器。
重點在2.2 handler中
一、resources
1.1 sqlMapConfig.xml
typeHandlers: 自定義的日期類型轉換器:
(1)將日期類型轉為long的長整型存入數據庫中。
(2)將數據庫中的bigint(本質對應java的long類型)轉為date類型。environments:加載數據庫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, stdout
1.3 userMapper.xml
1.findByid: 通過id查詢插入元素
2.save: xml映射器mapper時,
useGeneratedKeys:值為true 並分別指定屬性:
keyProperty: 對應的Java對象的主鍵屬性
keyColumn: 對應的數據庫記錄主鍵字段
<?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結構
2.1 dao
UserMapper
1.findByid: 使用id值查詢User
2.save: 插入User到數據庫中
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類型 轉換成 數據庫需要的類型
- getNullableResult:將數據庫中類型 轉換成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類型 轉換成 數據庫需要的類型 public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException { long time = date.getTime(); preparedStatement.setLong(i,time); } //將數據庫中類型 轉換成java類型 //String參數 要轉換的字段名稱 //ResultSet 查詢出的結果集 public Date getNullableResult(ResultSet resultSet, String s) throws SQLException { //獲得結果集中需要的數據(long) 轉換成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沒用進行實現,在本demo中隻用於測試使用。
sqlSession.commit()用於mybatis的事務提交。mybatis的事務默認是不提交的,故在增刪改中需要進行事務的提交,在mybatis中事務的提交方式一般有兩種:
1 sqlSession.commit()
2 采用openSession(true),即可實現自動提交,無需調用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則自動提交事務 SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(); //插入不需要設置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); } }
三 數據表結構及測試
數據表結構
測試
到此這篇關於使用 mybatis 自定義日期類型轉換器的文章就介紹到這瞭,更多相關mybatis 自定義日期類型轉換器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Java MyBatis框架環境搭建詳解
- 淺談MyBatis執行SQL的兩種方式
- 詳細聊聊Mybatis中萬能的Map
- MyBatis多表操作查詢功能
- mybatis使用resultMap獲取不到值的解決方案