场景一:有个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