问题描述:
SpringBoot + Mybatis项目中使用mybatis获取数据转换成实体类时,当实体类中存在枚举类型的属性(数据库中以数字格式存放),报错如下:
Cause: java.lang.IllegalArgumentException: No enum constantXXXXXX
转换的实体类如下:
@Data
public class vo1 {
private int id;
private String conf;
private String schema;
private String table;
private CheckType checkType;
private Date createTime;
private Date updateTime;
}
CheckType如下:
public enum CheckType {
/**
* binlog
*/
TEST(0),
/**
* SDK
*/
PROD(1);
private final int type;
CheckType(int type) {
this.type = type;
}
public int getType() {
return type;
}
private static boolean isExists(int type) {
for (CheckType obj : CheckType.values()) {
if (obj.getType() == type) {
return true;
}
}
return false;
}
}
原有的select:
<select id="xxx" resultType="路径.vo1">
select `id`,
`conf`,
`schema`,
`table`,
`check_type` as checkType,
`created_at` as createTime,
`updated_at` as updateTime
from `sync_platform`.`sync_data_transform_conf_settings`
where `enable` = 1
</select>
解决方法:
在map.xml文件中添加ResultMap配置,对需要枚举转换的字段配置特定的转换类EnumOrdinalTypeHandler
<?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="xxx">
<resultMap id="voMap" type="路径.vo1" >
<id column="id" property="id"/>
<result column="check_type" property="checkType" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
</resultMap>
<select id="xxx" resultMap="voMap">
select `id`,
`conf`,
`schema`,
`table`,
`check_type`,
`created_at` as createTime,
`updated_at` as updateTime
from `sync_platform`.`sync_data_transform_conf_settings`
where `enable` = 1
</select>
</mapper>
1:查询中resultType修改为ResultMap,否则会报 can not find class XXX
2:此处Result属性中,column对应的是数据库中字段,property是实体类中属性,项目中使用了数据库中_+小写转换为大写驼峰写法的配置
需要注意的是:select 中的resultType需要转换成resultMap中定义的名称 获取字段如果使用的是别名 必须在上面的resultMap中也使用别名,否则识别不出来,例如我原有的select中是checkType,下面配置的resultMap中的是check_type,此时就识别不了,去除别名即可
相关链接:(10条消息) SpringBoot+Mybatis使用Enmu枚举类型总是报错 No enum constant XX解决办法_Damionew的博客-CSDN博客_mybaits枚举报错