首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MyBatis中将整数转换为枚举?

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

Stack Overflow用户
提问于 2018-10-09 18:36:51
回答 1查看 904关注 0票数 0

我有以下几点:

代码语言:javascript
复制
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();
代码语言:javascript
复制
@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);
代码语言:javascript
复制
    Stat s = statMapper.findById(1);
    response.getOutputStream().print(s.toString());

它仍然给出了这个错误:

由Handler执行引起的解析异常: org.mybatis.spring.MyBatisSystemException:嵌套异常是试图从结果集获取列'hit_type‘的org.mybatis.spring.MyBatisSystemException错误。原因: java.lang.IllegalArgumentException:没有枚举常量com.company.app.model.Stat.HitType.2

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

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

代码语言:javascript
复制
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.Integer、java.math.BigInteger中找不到构造函数

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

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

MyBatis 3.4.5,MyBati-Spring1.3.1,Spring-Boot1.5.13

EN

回答 1

Stack Overflow用户

发布于 2018-10-09 19:43:05

我为这种类型添加了getter & setter。

代码语言:javascript
复制
public HitType getHitType() {
    return hitType;
}

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52727374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档