mybatis 自定义日期类型转换器
Le`soleil 人气:1前言
使用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); } }
三 数据表结构及测试
数据表结构
测试
加载全部内容