繁体   English   中英

如何在MyBatis中将整数转换为枚举?

[英]How do I convert an integer to an enum in 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,并读取了将整数值转换为匹配的Java Enum的信息

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

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

然后给出错误

嵌套的异常是org.apache.ibatis.executor.ExecutorException:在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

我为该类型添加了getter和setter

public HitType getHitType() {
    return hitType;
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM