SpringBoot+Mybatis使用Enmu枚举类型总是报错 No enum constant XX解决办法

环境SpringBoot+Mybatis

比如:

数据库中User表存放status字段值为1,想要通过Mybatis转换后为正在使用

当然,可以使用if else 但是状态值很多时,就变得很复杂,且不利于维护,故需要用到枚举类

数据库查询时获得status值为1,通过Mybatis依照枚举类进行转换获取到对应的状态

之前使用时总是报错:

Wed Jan 02 10:59:18 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
nested exception is org.apache.ibatis.executor.result.ResultMapException:
 Error attempting to get column 'qu_type' from result set.
 Cause: java.lang.IllegalArgumentException: No enum constant com.test.model.survey.QuType.1

此时的实体类代码如下:

public class Question {
	private String id;
	// 类型
	private QuType quType;
    。。get set
}

枚举类代码:

public enum QuType {

	YESNO("是否","yesno", 0);
	
	private String quName;
	private String quEnName;
	private int index;
	
	QuType(String quName,String quEnName,int index){
		this.cnName=quName;
		this.quEnName=quEnName;
		this.index=index;
	}

	..get set
}

Mybatis文件如下

<?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.test.mapper.QuestionMapper">
	
	<select id="getQuestionById" resultType="Question">
		SELECT * FROM question WHERE id = #{Id}
	</select>
	
</mapper>

此时就会报错:No enum constant com.test.model.survey.QuType.1

原因是无法使用Mybatis默认的转换器EnumTypeHandler 进行转换,解决方法:

只需要修改mybatis文件,添加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="com.test.mapper.QuestionMapper">
	
    <resultMap id="questionMap" type="com.test.model.survey.Question" >
	    <id column="id" property="id"/>
	    <result column="qu_type" property="quType" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
	   
	</resultMap>
	<select id="getQuestionById" resultMap="questionMap">
		SELECT * FROM question WHERE id = #{Id}
	</select>
	
</mapper>

注意!:

1:查询中resultType修改为ResultMap,否则会报 can not find class XXX

2:此处Result属性中,column对应的是数据库中字段,property是实体类中属性,项目中使用了数据库中_+小写转换为大写驼峰写法的配置

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值