使用Hibernate映射Enum值

时间:2015-06-22 10:48:59

标签: java hibernate jpa enums

我想用hibernate映射Enum的值来从DB中获取数据。 在数据库列**EASE_RATING** is number[1]中。我可以将DB中的数据保存为数字。

但是当我通过Criteria.list()检索数据时,我得到 easeRating =两个而不是 easeRating = 2

我的问题是如何以序数或枚举值的形式获取数据。

public enum Rating {

    Zero(0), // [No use] Taken Zero B'Coz Ordinal starts with 0
    One(1),
    ...
    Five(5);

    private final int value;

    Rating(int value){
        this.value = value;
    }

    public int getValue(){
        return this.value;
    }

    public static Rating getRating(int x) {
        switch(x) {
            case 1: return One; ...
            case 5: return Five;
        }
        return One;
    }
}

POJO:

@Enumerated(EnumType.ORDINAL)
@Column(name = "EASE_RATING", nullable = false)
private Rating easeRating;

更新

我想在Hibernate List()中的int [ordinal()]中使用此值。 我正在通过休眠来打击数据库。

List<CustomerFeedback> result = criteria.list();

我可以实现价值th **getValue()**

System.out.println(Rating.Five.getValue()); // 5
System.out.println(Rating.Five);            // Five
System.out.println(Rating.Five.name());     // Five

但是我如何在Hibernate list()

中得到它

2 个答案:

答案 0 :(得分:2)

Hibernate工作正常。你的问题是关于Enum。 toString()默认实现返回枚举的名称。这个名字是enum的文字:&#34; One&#34;,&#34; Two&#34;等...

如果你想获得一个枚举为1的枚举的序数,你必须创建一个新方法,因为ordinal()是最终的:

    /**
     * One-starting index enumeration
     */
    public enum Rating {

        One, Two, Three, Four;

        public int position() {
            return ordinal() + 1;
        }

        public static Rating getRating(int x) {
            return Rating.values()[x - 1];
        }

        public static void main(String args[]) {
            Rating one = Rating.One;
            System.out.println("ToString() (name): " + one);
            System.out.println("Ordinal position stating in 1: " + one.position());
        }

    }

回答更新1: 为什么不将评级列表映射到值列表?

    List<Rating> ratings = Arrays.asList(Rating.values());
    List<Integer> ints = ratings.stream()
            .mapToInt(Rating::position)
            .boxed()
            .collect(Collectors.toList());

答案 1 :(得分:0)

我不确定为什么需要原始数据库数据;我的建议是你应该总是使用Rating枚举,并在你需要的用例中从其实例中获取序数/值。

但是,满足您要求的解决方案之一可能是使用以下映射将另一个实体映射到同一个表:

@Column(name = "EASE_RATING", nullable = false)
private Integer easeRating;

还包括此实体中的任何其他所需列(在此用例中使用的列)。然后在查询中使用此实体。