【问题标题】:How do I convert an integer to an enum in MyBatis?如何在 MyBatis 中将整数转换为枚举?
【发布时间】:2018-10-09 18:36:51
【问题描述】:

我有以下几点:

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());

它仍然给出这个错误:

已解决由 Handler 执行引起的异常: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 matching [java.math.BigInteger, java.lang.String, java.sql.Timestamp, java .lang.Integer, java.math.BigInteger]

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

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

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

【问题讨论】:

    标签: java enums mybatis spring-mybatis


    【解决方案1】:

    我为该类型添加了 getter 和 setter

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多