[英]Mapping Enum value with Hibernate
我想用 hibernate 映射 Enum 的值以從 DB 獲取數據。 在數據庫列**EASE_RATING** is number[1]
。 我可以將數據庫中的數據保存為數字。
但是當我通過 Criteria.list() 檢索數據時,我得到了easieRating=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()] 中。 我正在通過休眠訪問 DB。
List<CustomerFeedback> result = criteria.list();
我可以通過**getValue()**
實現價值
System.out.println(Rating.Five.getValue()); // 5
System.out.println(Rating.Five); // Five
System.out.println(Rating.Five.name()); // Five
但是我如何在 Hibernate list() 中得到這個
休眠工作正常。 你的問題是關於枚舉。 toString() 默認實現返回枚舉的名稱。 名稱是枚舉的字面量:“一”、“二”等......
如果你想獲得一個用 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());
我不確定您為什么需要原始數據庫數據; 我的建議是,您應該始終使用Rating
枚舉,並在需要的用例中從其實例中獲取序數/值。
但是,滿足您要求的解決方案之一可能是使用以下映射將另一個實體映射到同一個表:
@Column(name = "EASE_RATING", nullable = false)
private Integer easeRating;
還包括此實體中的任何其他所需列(您在此用例中使用的列)。 然后在查詢中使用這個實體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.