mybatis-自定義typeHandler
阿新 • • 發佈:2018-09-07
定義 read 不同 net copy erb ava time() lis
場景一:有個java.util.Date在存入數據庫的時候自動轉換為timestamp時間戳,從數據庫取值的時候把時間戳自動轉換為java.util.Date
表結構
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `userAge` int(11) DEFAULT NULL, `userAddress` varchar(200) DEFAULT NULL, `reg_time` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
一、自定義typeHandler 直接實現 TypeHandler<T> 也可以繼承 BaseTypeHandler<T>,我們選擇繼承吧。
package com.yihaomen.mybatis.type; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; /** * * @ProjectName: springmvc-mybatis * @Description: 自定義處理日期Hander, * 將Date類型轉換為時間戳字符串戳存入到數據庫中 * 1.@MappedJdbcTypes定義的是JdbcType類型,這裏的類型不可自己隨意定義, * 必須要是枚舉類org.apache.ibatis.type.JdbcType所枚舉的數據類型。 * 2.@MappedTypes定義的是JavaType的數據類型,描述了哪些Java類型可被攔截。 * 3.在我們啟用了我們自定義的這個TypeHandler之後,數據的讀寫都會被這個類所過濾 */ @MappedTypes({Date.class}) @MappedJdbcTypes(JdbcType.VARCHAR) public class MyDateTypeHandler extends BaseTypeHandler<Date> { /** * 將時間戳字符串存入數據庫 */ @Override public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, String.valueOf(parameter.getTime())); } /** * 把時間戳類型的字符串取出轉換為Date */ @Override public Date getNullableResult(ResultSet rs, String columnName) throws SQLException { return new Date(rs.getLong(columnName)); } /** * 把時間戳類型的字符串取出轉換為Date */ @Override public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return new Date(rs.getLong(columnIndex)); } /** * 把時間戳類型的字符串取出轉換為Date */ @Override public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getDate(columnIndex); } }
二、在User.xml文件中寫<resultMap/>、<select/>和<insert/>
<?xml version="1.0" encoding="UTF-8" ?> <resultMap id="resultListUser" type="User"> <id column="id" property="id" /> <result column="userName" property="userName" /> <result column="userAge" property="userAge" /> <result column="userAddress" property="userAddress" /> <result column="reg_time" property="regTime" javaType="java.util.Date" jdbcType="VARCHAR" typeHandler="com.yihaomen.mybatis.type.MyDateTypeHandler"/> </resultMap> <select id="selectUserById2" parameterType="int" resultMap="resultListUser"> select * from user where id = #{id} </select> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(userName,userAge,userAddress,reg_time) values(#{userName},#{userAge}, #{userAddress}, #{regTime,javaType=Date,jdbcType=VARCHAR,typeHandler=com.yihaomen.mybatis.type.MyDateTypeHandler}) </insert>
三、寫UserMapper
package com.yihaomen.mybatis.dao; import com.yihaomen.mybatis.model.User; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserMapper { public User selectUserById2(int id); public void addUser(User user); }
三、測試一下
import com.yihaomen.mybatis.dao.UserMapper; import com.yihaomen.mybatis.model.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.Reader; import java.util.Date; /**
* 添加
*/ public class TestAddUser { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } public static SqlSessionFactory getSession() { return sqlSessionFactory; } public static void main(String[] args) { addUser(); } public static void addUser() { User user = new User(); user.setUserName("spring"); user.setUserAge("101"); user.setUserAddress("hangzhou,xihu"); user.setRegTime(new Date()); SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userMapper = session.getMapper(UserMapper.class); userMapper.addUser(user); session.commit(); System.out.println("當前增加的用戶 id為:" + user.getId()); } catch (Exception e) { session.rollback(); }finally { session.close(); } } }
package user; import com.yihaomen.mybatis.dao.UserMapper; import com.yihaomen.mybatis.model.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.Reader; import java.util.List; /** * * @ProjectName: springmvc-mybatis * @Description: 查找 */ public class TestGetUser { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } public static SqlSessionFactory getSession() { return sqlSessionFactory; } public static void findUserById(int id){ SqlSession session = sqlSessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); List<User> users = userMapper.selectUserById2(id); for(User u : users) { System.out.println(u.getRegTime()); } } public static void main(String[] args) { findUserById(3); } }
在configuration.xml中註冊typeHandler
<?xml version="1.0" encoding="UTF-8" ?> <!-- 註冊typeHandler,註冊有兩種不同的方式 1.可以像下面這樣一個類一個類的註冊 --> <typeHandlers> <typeHandler handler="com.yihaomen.mybatis.type.MyDateTypeHandler" /> </typeHandlers> <!--2.也可以直接註冊一個包中所有的typeHandler--> <!--<typeHandlers> <package name="com.yihaomen.mybatis.type"/> </typeHandlers>-->
這樣配置完成之後,當我們進行數據庫的讀取操作的時候,秒數就會自動轉為Date對象。
https://gitee.com/huayicompany/springmvc-mybatis.git
參考文獻:
[1] 楊開振 著,《深入淺出MyBatis技術原理與實戰》, 電子工業出版社,2016.09
[2] 個人博客,http://blog.csdn.net/u012702547/article/details/54572679
mybatis-自定義typeHandler