首页 > 解决方案 > 如何在 MyBatis 中将整数转换为枚举?

问题描述

我有以下内容:

public class Stat {

    public enum HitType {
        MOBILE1(0), MOBILE2(1), DESKTOP(2);
        public final int value;
        public int value() { return value; }
        HitType(int val) {
            value = val;
        }
        public static HitType parseInt(int i) {
            switch (i) {
                case 0: return MOBILE1;
                case 1: return MOBILE2;
                case 2: return DESKTOP;
                default: return null;
            }
        }
    }

    public HitType hitType;
    public long sourceId;

    public Stat(... int hitType, BigInteger sourceId) {
        this.hitType = HitType.parseInt(hitType);
        this.sourceId = sourceId.longValueExact();

@Mapper
public interface StatMapper {

    @Select("select * from stats where id = #{id}")
    @Results(value = {
        @Result(property = "hitType", column = "hit_type"),
        ...
        })
    public Stat findById(@Param("id") long id);

    Stat s = statMapper.findById(1);
    response.getOutputStream().print(s.toString());

它仍然给出这个错误:

处理程序执行导致的已解决异常:org.mybatis.spring.MyBatisSystemException:嵌套异常是 org.apache.ibatis.executor.result.ResultMapException:尝试从结果集中获取列“hit_type”时出错。原因:java.lang.IllegalArgumentException:没有枚举常量 com.company.app.model.Stat.HitType.2

我尝试了http://stackoverflow.com/questions/5878952/ddg#5878986并阅读Convert integer value to matching Java Enum

如果我将构造函数签名更改为

public Stat(..., int hitType, long sourceId) {
    this.sourceId = sourceId;

然后它给出了错误

嵌套异常是 org.apache.ibatis.executor.ExecutorException: No constructor found in com.company.app.model.Stat 匹配 [java.math.BigInteger, java.lang.String, java.sql.Timestamp, java.lang.整数,java.math.BigInteger]

因此,在第一种情况下,它可能直接设置属性,而在第二种情况下,它正在使用构造函数。

我尝试HitType hitType输入构造函数签名,但它仍然给我No constructor found...错误。

MyBatis 3.4.5、MyBatis-Spring 1.3.1、Spring-Boot 1.5.13

标签: javaenumsmybatisspring-mybatis

解决方案


我为该类型添加了 getter & setter

public HitType getHitType() {
    return hitType;
}

public void setHitType(int hitType) {
    this.hitType = HitType.parseInt(hitType);
}

然后它开始工作。这很奇怪,因为它抱怨构造函数签名。如果它使用构造函数,为什么需要 getter 和 setter?


推荐阅读