我想将 Enum 的值与 hibernate 映射以从数据库获取数据。
在数据库列中,**EASE_RATING** 为数字[1]
。我能够将数据作为数字保存在数据库中。
但是当我通过 Criteria.list() 检索数据时,我得到的是 easeRating=Two 而不是 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()] 中的值。 我正在通过 hibernate 访问数据库。
List<CustomerFeedback> result = criteria.list();
我可以通过**getValue()**实现值(value)
System.out.println(Rating.Five.getValue()); // 5
System.out.println(Rating.Five); // Five
System.out.println(Rating.Five.name()); // Five
但是我如何在 Hibernate list() 中得到这个
最佳答案
hibernate 工作正常。你的问题是关于枚举的。 toString() 默认实现返回枚举的名称。名称是枚举的文字:“One”、“Two”等...
如果你想获得以 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());
关于java - 使用 Hibernate 映射 Enum 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30978045/