解决SpringBoot+MyBatis枚举类型转换问题
问题分析:在整合SpringBoot和MyBatis的时候,我们偶尔会涉及到枚举类型的转换,如果在整合的过程中不做任何的操作会出什么问题呢?
实体类:
@Data
public class Termination {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String workId;
private String employeeName;
private Integer employeeId;
private String content;
private String handleName;
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai")
private LocalDate crateTime;
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai")
private LocalDate solveTime;
private TerminationStatusEnum status;
@TableField(exist = false)
private Employee employee;
}
枚举类:
public enum TerminationStatusEnum {
PenDingReview(0,"待审核"),
ReviewPass(1,"审核通过"),
ReviewError(2,"不通过");
TerminationStatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
};
@EnumValue
private Integer code;
private String msg;
}
? MyBatis.xml
<resultMap id="BaseResultMap" type="com.lqqgust.kumeperson.entity.Termination">
<result column="id" property="id"/>
<result column="workId" property="workId"/>
<result column="employeeName" property="employeeName"/>
<result column="employeeId" property="employeeId"/>
<result column="content" property="content"/>
<result column="handleName" property="handleName"/>
<result column="crateTime" property="crateTime"/>
<result column="solveTime" property="solveTime"/>
<result column="status" property="status"/>
</resultMap>
接下来我们在执行查询语句的时候会出现一个问题,报了个No enum constant,原因是我们没有对枚举类进行类型的转换,MyBatis不能自动帮我们转。。
但是MyBatis提供了个自动转换枚举类处理器org.apache.ibatis.type.EnumOrdinalTypeHandler ,我们根据MyBatis自带的处理器就可以解决枚举类型的转换问题 ,而无需在写个处理器,极大方便我们的开发。
解决方案:
只要在需要转换的字段上加上typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler 就可以解决了!
返回结果:
数据库:
|