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文件如下




	
	
	

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

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

只需要修改mybatis文件,添加ResultMap配置,对需要枚举转换的字段配置特定的转换类EnumOrdinalTypeHandler 

如下:




	
    
	    
	    
	   
	
	
	

注意!:

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

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

你可能感兴趣的:(SpringBoot,SpringBoot使用说明书)