之前我们介绍了使用Mybatis完成数据的增删改查操作;本篇我们介绍使用Mybatis提供的typeHandler自定义类型转换。
如果您对Mybatis的增删改查操作不太了解,可以参考:
Mybatis 查询数据https://blog.csdn.net/m1729339749/article/details/132469672Mybatis 插入、修改、删除https://blog.csdn.net/m1729339749/article/details/132601345
一、数据准备
这里我们直接使用脚本初始化数据库中的数据
- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建用户表
CREATE TABLE IF NOT EXISTS T_TEACHER(
ID INT PRIMARY KEY COMMENT '教师编号',
TEACHER_NAME VARCHAR(64) NOT NULL COMMENT '教师名称',
DEPARTMENT VARCHAR(16) NOT NULL COMMENT '所属部门',
BIRTH DATE NOT NULL COMMENT '出生年月',
DEGREE ENUM('ZK','BK','YJS','BS') NOT NULL COMMENT '学历(ZK:专科, BK:本科, YJS:研究生, BS:博士)'
);
-- 插入用户数据
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
VALUES(1, '张三1', '001', '1990-06-12', 'BK'),
(2, '李四1', '002', '1992-05-10', 'BK'),
(3, '张三2', '003', '1988-01-15', 'YJS'),
(4, '李四2', '001', '1979-03-10', 'BK'),
(5, '李四3', '003', '1995-08-16', 'YJS');
创建了一个名称为demo的数据库;并在库里创建了名称为T_TEACHER的教师表并向表中插入了数据
注意:教师表中的DEGREE字段是枚举类型
二、环境搭建
1、创建实体类
在cn.horse.demo下创建TeacherInfo实体类:
TeacherInfo类:
package cn.horse.demo;
import java.time.LocalDate;
public class TeacherInfo {
private Integer id;
private String name;
private String department;
private LocalDate birth;
private Degree degree;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDepartment() {
return department;
}
public void setBirth(LocalDate birth) {
this.birth = birth;
}
public LocalDate getBirth() {
return birth;
}
public void setDegree(Degree degree) {
this.degree = degree;
}
public Degree getDegree() {
return degree;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{ ");
stringBuilder.append("id: ");
stringBuilder.append(this.id);
stringBuilder.append(", ");
stringBuilder.append("name: ");
stringBuilder.append(this.name);
stringBuilder.append(", ");
stringBuilder.append("department: ");
stringBuilder.append(this.department);
stringBuilder.append(", ");
stringBuilder.append("birth: ");
stringBuilder.append(this.birth);
stringBuilder.append(", ");
stringBuilder.append("degree: ");
stringBuilder.append(this.degree);
stringBuilder.append(" }");
return stringBuilder.toString();
}
}
Degree枚举类:
package cn.horse.demo;
public enum Degree {
// 专科
COLLEGE,
// 本科
BACHELOR,
// 研究生
GRADUATE,
// 博士
DOCTORAL
}
2、Mapper配置文件
在resources的目录下新建TeacherInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.TeacherInfoMapper">
<resultMap id="teacherInfoMap" type="cn.horse.demo.TeacherInfo">
<result column="ID" property="id" />
<result column="TEACHER_NAME" property="name" />
<result column="DEPARTMENT" property="department" />
<result column="BIRTH" property="birth" />
<result column="DEGREE" property="degree" />
</resultMap>
<select id="findAll" resultMap="teacherInfoMap">
SELECT
ID,
TEACHER_NAME,
DEPARTMENT,
BIRTH,
DEGREE
FROM T_TEACHER
</select>
<insert id="insert" parameterType="cn.horse.demo.TeacherInfo">
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
VALUES(#{id}, #{name}, #{department}, #{birth}, #{degree})
</insert>
</mapper>
3、引入配置文件
在resources下新建mybatis-config.xml配置文件,并引入TeacherInfoMapper.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>
<settings>
<setting name="logImpl" value="JDK_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="horse"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="demo/TeacherInfoMapper.xml" />
</mappers>
</configuration>
4、会话工具类
在cn.horse.demo包下新建SqlSessionUtils工具类
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.Objects;
public class SqlSessionUtils {
private static final SqlSessionFactory sqlSessionFactory;
static {
// 读取mybatis配置文件
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
// 根据配置创建SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
}
/**
* 开启会话
* @return
*/
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
/**
* 关闭会话
* @param sqlSession
*/
public static void closeSession(SqlSession sqlSession) {
if(Objects.nonNull(sqlSession)) {
sqlSession.close();
}
}
}
5、JDK 日志系统配置
在resources的目录下新建logging.properties配置文件
handlers=java.util.logging.ConsoleHandler
.level=INFO
cn.horse.demo.TeacherInfoMapper.level=FINER
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tT.%1$tL %4$s %3$s - %5$s%6$s%n
在cn.horse.demo下新建JdkLogConfig类:
JdkLogConfig类:
package cn.horse.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
public class JdkLogConfig {
public JdkLogConfig() {
try {
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
LogManager.getLogManager().readConfiguration(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
6、启动程序配置
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import java.time.LocalDate;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
}
}
三、数据转换存在的问题
1、例子:查询教师列表
添加查询教师列表的静态方法
private static void findAll(String statement) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
List<TeacherInfo> teacherInfoList = sqlSession.selectList(statement);
for (TeacherInfo teacherInfo: teacherInfoList) {
System.out.println(teacherInfo);
}
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
调用查询教师列表的方法
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
findAll("cn.horse.demo.TeacherInfoMapper.findAll");
执行后的结果如下:
2023-09-04 16:26:40.114 详细 cn.horse.demo.TeacherInfoMapper.findAll - ==> Preparing: SELECT ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE FROM T_TEACHER
2023-09-04 16:26:40.163 详细 cn.horse.demo.TeacherInfoMapper.findAll - ==> Parameters:
2023-09-04 16:26:40.176 较详细 cn.horse.demo.TeacherInfoMapper.findAll - <== Columns: ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE
2023-09-04 16:26:40.180 较详细 cn.horse.demo.TeacherInfoMapper.findAll - <== Row: 1, 张三1, 001, 1990-06-12, BK
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'DEGREE' from result set. Cause: java.lang.IllegalArgumentException: No enum constant cn.horse.demo.Degree.BK
### The error may exist in demo/TeacherInfoMapper.xml
### The error may involve cn.horse.demo.TeacherInfoMapper.findAll
### The error occurred while handling results
### SQL: SELECT ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE FROM T_TEACHER
### Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'DEGREE' from result set. Cause: java.lang.IllegalArgumentException: No enum constant cn.horse.demo.Degree.BK
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:136)
at cn.horse.demo.Main.findAll(Main.java:29)
at cn.horse.demo.Main.main(Main.java:12)
Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'DEGREE' from result set. Cause: java.lang.IllegalArgumentException: No enum constant cn.horse.demo.Degree.BK
at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:68)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getPropertyMappingValue(DefaultResultSetHandler.java:467)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyPropertyMappings(DefaultResultSetHandler.java:436)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:399)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap(DefaultResultSetHandler.java:351)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:326)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:299)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:192)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:64)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
... 4 more
Caused by: java.lang.IllegalArgumentException: No enum constant cn.horse.demo.Degree.BK
at java.base/java.lang.Enum.valueOf(Enum.java:273)
at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:49)
at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:26)
at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:66)
... 19 more
分析:
从数据库表中查询出来的学历数据无法在Degree学历枚举类型中找到
2、例子:新增教师
添加新增教师的静态方法
private static void insert(String statement, TeacherInfo teacherInfo) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.insert(statement, teacherInfo);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
调用新增教师的方法
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(11);
teacherInfo.setName("张三1");
teacherInfo.setDepartment("001");
teacherInfo.setBirth(LocalDate.of(1998, 10, 20));
teacherInfo.setDegree(Degree.DOCTORAL);
insert("cn.horse.demo.TeacherInfoMapper.insert", teacherInfo);
执行后的结果如下:
2023-09-04 16:28:58.817 详细 cn.horse.demo.TeacherInfoMapper.insert - ==> Preparing: INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE) VALUES(?, ?, ?, ?, ?)
2023-09-04 16:28:58.875 详细 cn.horse.demo.TeacherInfoMapper.insert - ==> Parameters: 11(Integer), 张三1(String), 001(String), 1998-10-20(Date), DOCTORAL(String)
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: java.sql.SQLException: Data truncated for column 'DEGREE' at row 1
### The error may involve cn.horse.demo.TeacherInfoMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE) VALUES(?, ?, ?, ?, ?)
### Cause: java.sql.SQLException: Data truncated for column 'DEGREE' at row 1
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:200)
at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:185)
at cn.horse.demo.Main.insert(Main.java:40)
at cn.horse.demo.Main.main(Main.java:20)
Caused by: java.sql.SQLException: Data truncated for column 'DEGREE' at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1915)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1254)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
at jdk.proxy3/jdk.proxy3.$Proxy3.execute(Unknown Source)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:46)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
... 3 more
分析:
Degree学历枚举类型的数据存储到数据库表中的字段时,无法将枚举类型的数据转换成数据库表中字段能够存储的数据
四、自定义数据类型转换
上面的两个示例中,我们从库中查询数据(读库)或者向库中插入数据(写库)都存在数据转换的问题,mybatis给我们提供了TypeHandler扩展,可以根据类型自定义读写库时数据的转换。
自定义DegreeTypeHandler:
package cn.horse.demo;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DegreeTypeHandler implements TypeHandler<Degree> {
@Override
public void setParameter(PreparedStatement ps, int i, Degree parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, formatDegree(parameter));
}
private String formatDegree(Degree degree) {
switch (degree) {
case COLLEGE:
return "ZK";
case BACHELOR:
return "BK";
case GRADUATE:
return "YJS";
case DOCTORAL:
return "BS";
}
return null;
}
@Override
public Degree getResult(ResultSet rs, String columnName) throws SQLException {
return parseDegree(rs.getString(columnName));
}
@Override
public Degree getResult(ResultSet rs, int columnIndex) throws SQLException {
return parseDegree(rs.getString(columnIndex));
}
@Override
public Degree getResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseDegree(cs.getString(columnIndex));
}
private Degree parseDegree(String degree) {
switch (degree) {
case "ZK":
return Degree.COLLEGE;
case "BK":
return Degree.BACHELOR;
case "YJS":
return Degree.GRADUATE;
case "BS":
return Degree.DOCTORAL;
}
return null;
}
}
TypeHandler提供了两类方法:setParameter方法用于设置SQL参数,getResult方法用于获取查询的结果
上述实现中,我们在setParameter方法中将Degree枚举类型的数据转换成数据库表中字段能够识别的数据设置到SQL参数中,可用于查询、新增、修改、查询等操作;在getResult方法中将从数据库表中查询到的字段对应的数据转换成Degree枚举类型的数据;
修改TeacherMapper.xml配置文件,目的是让查询数据、新增数据时,使用自定义的DegreeTypeHandler
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.TeacherInfoMapper">
<resultMap id="teacherInfoMap" type="cn.horse.demo.TeacherInfo">
<result column="ID" property="id" />
<result column="TEACHER_NAME" property="name" />
<result column="DEPARTMENT" property="department" />
<result column="BIRTH" property="birth" />
<result column="DEGREE" property="degree" typeHandler="cn.horse.demo.DegreeTypeHandler" />
</resultMap>
<select id="findAll" resultMap="teacherInfoMap">
SELECT
ID,
TEACHER_NAME,
DEPARTMENT,
BIRTH,
DEGREE
FROM T_TEACHER
</select>
<insert id="insert" parameterType="cn.horse.demo.TeacherInfo">
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
VALUES(#{id}, #{name}, #{department}, #{birth}, #{degree,typeHandler=cn.horse.demo.DegreeTypeHandler})
</insert>
</mapper>
查询数据时,在resultMap结果映射的result标签中配置typeHandler属性
新增数据时,在SQL中使用参数时配置TypeHandler,格式如下:
#{degree,typeHandler=cn.horse.demo.DegreeTypeHandler}
1、例子:查询教师列表
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
findAll("cn.horse.demo.TeacherInfoMapper.findAll");
执行后的结果如下:
2、例子:新增教师
private static void insert(String statement, TeacherInfo teacherInfo) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.insert(statement, teacherInfo);
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
执行后的结果如下: