SpringBoot集成Mybatis枚举类型转换
一、前言
数据库表中的列通常选择存储数字,而与数据库表对应的实体类中的相应字段,为避免出现魔法值的情况,通常使用枚举类型来替代。在进行数据持久化操作时,数据库表中的数字与实体类中的枚举类型之间必然会出现类型转换问题。
二、解决方案
以高校学生的学历类型为例,编写枚举类进行演示。其中包括bachelor、master和college三类,分别代表本科、硕士和博士,存入数据库中的值对应为了1、2和3。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @Getter public enum XueliType { BACHELOR(1, "本科"), MASTER(2, "硕士"), COLLEGE(3, "专科");
private final int code;
private final String desc;
XueliType(int code, String desc) { this.code = code; this.desc = desc; }
@JsonCreator public static XueliType fromCode(int code) { for (XueliType xueliType : XueliType.values()) { if (xueliType.code == code) { return xueliType; } } throw new IllegalArgumentException("Invalid status code: " + code); } }
|
使用@JsonCreator注解能够在Controller层接收前端参数时,根据code匹配枚举值并自动返回对应枚举值。
1.方案一:使用MybatisPlus注解
原始的Myabits框架上并不能直接解决类型转换问题,在其基础上做了全面增强的MybatisPlus框架,支持通过注解的方式轻松解决。
使用@EnumValve注解,添加到枚举类型的字段上时,该字段将会作为存入数据库中的具体值。
1 2 3 4 5 6 7 8 9 10 11
| @Getter public enum XueliType {
@EnumValve private final int code;
private final String desc;
}
|
此时,无论增删改查等数据库操作,凡是涉及XueliType字段的操作,MybatisPlus都将以code字段的值为依据进行处理。
2.方案二:仅使用Mybatis框架
出于多种原因,存在部分开发环境下不允许使用MybatisPlus框架的情况。仅使用Mybatis框架则需要更多的步骤,但依然能完美解决。
1)编写枚举类型处理器
在Mybatis框架内部提供了抽象类BaseTypeHandler,专门用于解决数据持久化操作时的类型转换操作。只需继承该类并实现其抽象方法,即可实现当前枚举类的类型转换操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| public class XueliTypeTypeHandler extends BaseTypeHandler<XueliType> {
@Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, XueliType xueliType, JdbcType jdbcType) throws SQLException { preparedStatement.setInt(i, xueliType.getCode()); }
@Override public XueliType getNullableResult(ResultSet resultSet, String s) throws SQLException { int code = resultSet.getInt(s); return XueliType.fromCode(code); }
@Override public XueliType getNullableResult(ResultSet resultSet, int i) throws SQLException { int code = resultSet.getInt(i); return XueliType.fromCode(code); }
@Override public XueliType getNullableResult(CallableStatement callableStatement, int i) throws SQLException { int code = callableStatement.getInt(i); return XueliType.fromCode(code); } }
|
2)注册为Mybatis配置
由于是SpringBoot所集成的Mybatis框架,编写好的枚举类型处理器需要注册为Bean对象,并添加至Mybaits配置类中才能生效。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Configuration public class MybatisConfig {
@Bean public XueliTypeTypeHandler xueliTypeTypeHandler() { return new XueliTypeTypeHandler(); } }
|
现在就已经可以完成枚举类型与数据库字段的类型转换,正确执行数据持久化操作了。
三、写在最后
Mybatis是当前最流行的数据持久化操作框架之一,当面临实体类和数据库表中的字段类型转换时,无论是否使用MybatisPlus,都可以通过对应的方式进行处理,从而应对不同的开发需求。