Mybatis-自定义类型处理器
类型转换器:mybatis中有一些常用的类型转换器,比如把Java中的short类型转换为mysql中的short类型;但是如果现在是Java中的Date类型,但是我想要存储到数据库中转换为Long类型的毫秒值(默认1970-00-00-00至今),就需要自己定义转换器
1.创建实体类User
public class User {
private int id;
private String username;
private String password;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
2.编写UserMapper.xml文件
<?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.hao.mapper.UserMapper">
<insert id="save" parameterType="user">
insert into user values(#{id},#{username},#{password},#{birthday})
</insert>
</mapper>
3.编写SqlMapConfig.xml文件
<?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>
<!-- 加载jdbc.properties配置文件-->
<properties resource="jdbc.properties"/>
<!-- 定义别名-->
<typeAliases>
<typeAlias type="com.hao.domain.User" alias="user"/>
</typeAliases>
<!-- 注册类型处理器-->
<typeHandlers>
<typeHandler handler="com.hao.handler.DateTypeHandler"/>
</typeHandlers>
<!-- 配置数据源环境-->
<environments default="development"><!-- 表示默认情况下使用id为development的环境-->
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件-->
<mappers>
<mapper resource="com/hao/mapper/UserMapper.xml"/>
</mappers>
</configuration>
4.自定义类型处理器(必须实现BaseTypeHandler类,泛型中的Date就是要转换的Java类型),实现其中的四个方法
public class DateTypeHandler extends BaseTypeHandler<Date> {
//将java类型转换为数据库需要的类型
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i,time);
}
//将数据库中的类型转化为Java类型
//String:要转换的字段的名称
//ResultSet:查询的结果集
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
//获取结果集中需要的数据(long)转换成Date类型
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
5.测试
public class MapperTest {
@Test
public void test1() throws IOException {
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(stream).openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("ceshi");
user.setPassword("abc");
user.setDate(new Date());
//执行保存
mapper.save(user);
sqlSession.commit();
}
}
6.结果
7.从数据库中读取出来
在UserMapper中添加查询sql语句
<?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.hao.mapper.UserMapper">
<insert id="save" parameterType="user">
insert into user values(#{id},#{username},#{password},#{date})
</insert>
<select id="findById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select>
</mapper>
8.测试
public class MapperTest {
@Test
public void test1() throws IOException {
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(stream).openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.findById(8);
System.out.println(user.getBirthday());
}
}
9.结果
Mybatis-自定义类型处理器的更多相关文章
- MyBatis 示例-类型处理器
MyBatis 提供了很多默认类型处理器,参考官网地址:链接,除了官网提供的类型处理器,我们也可以自定义类型处理器. 具体做法为:实现 org.apache.ibatis.type.TypeHandl ...
- mybatis 自定义类型转换器 (后台日期类型插入数据库)
后台日期类型插入数据库 有以下几种发法: 1 调用数据库 日期字符串转日期函数 str_to_date("日期","yyyy-MM-dd HH:mm:ss") ...
- Mybatis的类型处理器
Mybatis在预处理语句(PreparedStatement)中设置一个参数时,会用默认的typeHandler进行处理. 这句话是什么意思呢,当你想用姓名查询一个人的信息时 <select ...
- mybatis枚举类型处理器
1. 定义枚举值的接口 public abstract interface ValuedEnum { int getValue(); } 所有要被mybatis处理的枚举类继承该接口 2. 定义枚举类 ...
- Mybatis中使用自定义的类型处理器处理枚举enum类型
知识点:在使用Mybatis的框架中,使用自定义的类型处理器处理枚举enum类型 应用:利用枚举类,处理字段有限,可以用状态码,代替的字段,本实例,给员工状态字段设置了一个枚举类 状态码,直接赋值给对 ...
- 浩哥解析MyBatis源码(九)——Type类型模块之类型处理器注册器(TypeHandlerRegistry)
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6709157.html 1.回顾 上一篇研究的是类型别名注册器TypeAliasRegist ...
- 浩哥解析MyBatis源码(十)——Type类型模块之类型处理器
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6715063.html 1.回顾 之前的两篇分别解析了类型别名注册器和类型处理器注册器,此二 ...
- MyBatis源码解析(十)——Type类型模块之类型处理器TypeHandler
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6715063.html 1.回顾 之前的两篇分别解析了类型别名注册器和类型处理器注册器,此二 ...
- MyBatis源码解析(九)——Type类型模块之类型处理器注册器(TypeHandlerRegistry)
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6709157.html 1.回顾 上一篇研究的是类型别名注册器TypeAliasRegist ...
- mybatis学习系列五--插件及类型处理器
2 插件编写(80-81) 单个插件编写 2.1实现interceptor接口(ibatis) invocation.proceed()方法执行必须要有,否则不会无法实现拦截作用 2.2 使用@int ...
随机推荐
- S5700上三层Vlan间隔离的例子
转自:https://forum.huawei.com/enterprise/zh/forum.php?mod=viewthread&tid=247591 公司最近的无线覆盖做好了,但让人无语 ...
- 从此 Typora 代码块有了颜色
起因 平时喜欢用typora记笔记,但是typora默认代码块没有指定语言,没有高亮看着很不舒服,所以用Autohotkey花了半天写了个脚本,按自己的快捷键就可以自动生成代码块并添加语言,这样就方便 ...
- 如何防止 IP 被盗用 保护网络正常运行
IP被盗用是指盗用者使用未经授权的IP来配置网上的计算机.目前IP盗用行为非常常见,许多"不法之徒"用盗用地址的行为来逃避追踪.隐藏自己的身份.IP的盗用行为侵害了网络正常用户的权 ...
- SpringCloud-Consul
1. Consul 简介 Consul是 HashiCorp 公司推出的开源工具,用于实现分布式系统的服务发现与配置.与其它分布式服 务注册与发现的方案,Consul 的方案更"一站式&qu ...
- 从SpringBoot到SpringCloudAlibaba简明教程(一):初识SpringBoot及其基础项目构建
前言 Spring框架的大名想必大家早已如雷贯耳,我们来看一下springboot诞生的初衷,以及它在springframe的基础上解决了哪些痛点. 很久以前,J2EE还是java企业级应用的标准规范 ...
- MapReduce: Simplified Data Processing on Large Clusters 翻译和理解
MapReduce: Simplified Data Processing on Large Clusters 概述 MapReduce 是一种编程模型,用于处理和生成大型数据集的相应实现.用户定义一 ...
- badusb
badusb介绍 BadUSB是利用伪造HID设备执行攻击载荷的一种攻击方式.HID(Human InterfaceDevice)设备通常指的就是键盘鼠标等与人交互的设备,用户插入BadUSB,就会 ...
- 类型转换Java day8
类型转换自动类型转换 从同种类型的低字节类型值直接转换到高类型字节值的转换可自动转换 类型自动转换示例 byte a = 20; int b = a;//不报错可正常转换 有些类型它在计算时默认以指定 ...
- 学习Spring资料
参考文档 官方文档 源码分析 书籍 Spring5核心原理与30个类手写实战 Spring技术内幕 视频 bilibili
- fiber核心(react 16)?
旧: 浏览器渲染引擎单线程, 计算DOM树时锁住整个线程, 所有行为同步发生, 有效率问题, 期间react会一直占用浏览器主线程,如果组件层级比较深,相应的堆栈也会很深,长时间占用浏览器主线程, 任 ...