mybatis的学习和使用--TypeHandler的使用(4)

使用mybatis提供的DateTypeHandler 代码路径--- https://github.com/wangjiuong/MybatisDemo/tree/master/MyBatisDateTypeHandlerTimeStamp

使用到的建表语句如下:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t_user_timestamp`
-- ----------------------------
DROP TABLE IF EXISTS `t_user_timestamp`;
CREATE TABLE `t_user_timestamp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `regTime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

使用自定义的TypeHandler的代码路径---https://github.com/wangjiuong/MybatisDemo/tree/master/MyBatisDateTypeHandler

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t_user_typehandler`
-- ----------------------------
DROP TABLE IF EXISTS `t_user_typehandler`;
CREATE TABLE `t_user_typehandler` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `regTime` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;

 

mybatis提供了另外一个强大的功能,就是可以在bean对象的属性和数据库中存储的对象属性进行转换,譬如bean中是list属性,存储到数据库中可以是array属性,bean中是java.util.Date属性,数据库中存储的是varchar类型的unix时间戳。

mybatis对于属性转换已经提供了较多的类,如果没有我们所需要的,可以自定义实现一个。属性转换类都实现接口类BaseTypeHandler<T>(package org.apache.ibatis.type;),并且需要实现其中的四个函数:

1 public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
2 
3   public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;
4 
5   public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;
6 
7   public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;

 

mybatis中已经提供的有如下:

 

 

使用起来其实比较简单,只需要在resultMap中定义转换类型就可以了。表示在获取查询结果生成bean对象的时候,使用org.apache.ibatis.type.DateTypeHandler进行处理。

 1 <mapper namespace="com.wang.MyBatis.model.UserMapper">
 2 <!-- 自定义返回结果集 -->
 3    <resultMap id="userMap" type="com.wang.MyBatis.model.UserBean">
 4         <id property="id" column="id" javaType="java.lang.Integer"></id>
 5         <result property="username" column="username" javaType="java.lang.String"></result>
 6         <result property="password" column="password" javaType="java.lang.String"></result>
 7         <result typeHandler="org.apache.ibatis.type.DateTypeHandler" column="regTime" javaType="java.util.Date"
 8                 jdbcType="VARCHAR"
 9                 property="regTime"/>
10     </resultMap>

在插入和更新的时候自定使用

    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user_timeStamp (username,password,regTime) values (#{username},#{password},#{regTime,typeHandler=org.apache.ibatis.type.DateTypeHandler})
    </insert>
    
    <update id="updateUser" >
      update t_user_timeStamp set username=#{username},password=#{password},regTime=#{regTime,typeHandler=org.apache.ibatis.type.DateTypeHandler} where id=#{id}
    </update>

#{regTime,typeHandler=org.apache.ibatis.type.DateTypeHandler} 表示在插入和更新regTime字段时,使用org.apache.ibatis.type.DateTypeHandler进行处理。

 

这个表示,在进行存储获取读取regTime字段的时候,用DateTypeHandler进行转换,mybatis的DateTypeHandler的实现如下:

 1 /**
 2  *    Copyright 2009-2015 the original author or authors.
 3  *
 4  *    Licensed under the Apache License, Version 2.0 (the "License");
 5  *    you may not use this file except in compliance with the License.
 6  *    You may obtain a copy of the License at
 7  *
 8  *       http://www.apache.org/licenses/LICENSE-2.0
 9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 package org.apache.ibatis.type;
17 
18 import java.sql.CallableStatement;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.sql.Timestamp;
23 import java.util.Date;
24 
25 /**
26  * @author Clinton Begin
27  */
28 public class DateTypeHandler extends BaseTypeHandler<Date> {
29 
30   @Override
31   public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType)
32       throws SQLException {
33     ps.setTimestamp(i, new Timestamp((parameter).getTime()));
34   }
35 
36   @Override
37   public Date getNullableResult(ResultSet rs, String columnName)
38       throws SQLException {
39     Timestamp sqlTimestamp = rs.getTimestamp(columnName);
40     if (sqlTimestamp != null) {
41       return new Date(sqlTimestamp.getTime());
42     }
43     return null;
44   }
45 
46   @Override
47   public Date getNullableResult(ResultSet rs, int columnIndex)
48       throws SQLException {
49     Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
50     if (sqlTimestamp != null) {
51       return new Date(sqlTimestamp.getTime());
52     }
53     return null;
54   }
55 
56   @Override
57   public Date getNullableResult(CallableStatement cs, int columnIndex)
58       throws SQLException {
59     Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
60     if (sqlTimestamp != null) {
61       return new Date(sqlTimestamp.getTime());
62     }
63     return null;
64   }
65 }

 

执行工程中的测试类,查看数据中数据如下:

 

读取数据中数据后输出的信息如下:

 

posted @ 2017-04-09 16:41  王久勇  阅读(9375)  评论(0编辑  收藏  举报