代码之家  ›  专栏  ›  技术社区  ›  Chloe

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

  •  0
  • Chloe  · 技术社区  · 6 年前

    我有以下几点:

    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.mybatissSystemException:嵌套异常为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;
    

    然后它给出了错误

    嵌套异常是Or.ApACH.iActudi.Excuto.ExcutoExcExcor:没有在COM.Po.App.Mealth.STAT匹配中找到的构造函数[java. Math.BigType,JavaLang.Stand,java. q.LimeType,JavaLang.Ongult,Java.Maul.BigInteger)

    因此,在第一种情况下,它似乎是直接设置属性,而在第二种情况下,它使用的是构造函数。

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

    Mybatis 3.4.5,Mybatis弹簧1.3.1,弹簧靴1.5.13

    1 回复  |  直到 6 年前
        1
  •  0
  •   Chloe    6 年前

    我为那个类型添加了getter和setter

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

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