环境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 :
Error attempting to get column 'qu_type' from result set.
Cause: : No enum constant .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){
=quName;
=quEnName;
=index;
}
..get set
}
Mybatis文件如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/" >
<mapper namespace="">
<select resultType="Question">
SELECT * FROM question WHERE id = #{Id}
</select>
</mapper>
此时就会报错:No enum constant .1
原因是无法使用Mybatis默认的转换器EnumTypeHandler 进行转换,解决方法:
只需要修改mybatis文件,添加ResultMap配置,对需要枚举转换的字段配置特定的转换类EnumOrdinalTypeHandler
如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/" >
<mapper namespace="">
<resultMap type="" >
<id column="id" property="id"/>
<result column="qu_type" property="quType" typeHandler=""/>
</resultMap>
<select resultMap="questionMap">
SELECT * FROM question WHERE id = #{Id}
</select>
</mapper>
注意!:
1:查询中resultType修改为ResultMap,否则会报 can not find class XXX
2:此处Result属性中,column对应的是数据库中字段,property是实体类中属性,项目中使用了数据库中_+小写转换为大写驼峰写法的配置