Java 如何使用 Hibernate 将枚举值保存到数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21971272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:45:49  来源:igfitidea点击:

how to save enum value to DB with Hibernate?

javamysqldatabasehibernateenums

提问by nazar_art

I tried to fill DB tables with random data and through Hibernate.

我试图用随机数据并通过 Hibernate 填充数据库表。

But my code fill incompatible data into tables (not exactly incompatible it is index of this element declared at enum, for ex: at ApartmentState- FREEis first element it set to appropriate column it index - 0. But I want to put or FREEas enum or as string).

但是我的代码将不兼容的数据填充到表中(并非完全不兼容,它是在枚举中声明的该元素的索引,例如:at ApartmentState-FREE是它设置为适当列的第一个元素,它的索引 - 0。但我想把或FREE作为枚举或作为细绳)。

I couldn't figure out why exactly this happen.

我无法弄清楚为什么会发生这种情况。

Here is code snippet:

这是代码片段:

private List<Apartment> generateApartments() {
        for (int i = 1; i <= 3; i++) {
            for (int j = 2; j <= 5; j++) {
                Apartment apartment = new Apartment();
                // fill apartment
                apartment.setRoomName(generateRoomName());
                apartment.setPricePerHour(generatePrice());
                apartment.setApartmentState(FREE);
                apartment.setRating(getDesiredRating(j));
                apartment.setSleepPlaces(getDesiredPlaces(i));
                apartment.setActive(true);
                // save apartment
                apartments.add(apartment);
            }
        }
        return apartments;
    }

    private Apartment.SleepPlaces getDesiredPlaces(int i) {
        switch (i) {
            case 1:
                return ONE_PLACE;
            case 2:
                return TWO_PLACES;
            case 3:
                return THREE_PLACES;
        }
        return ONE_PLACE;
    }

    private Apartment.StarRating getDesiredRating(int j) {
        switch (j) {
            case 2:
                return TWO_STARS;
            case 3:
                return THREE_STARS;
            case 4:
                return FOUR_STARS;
            case 5:
                return FIVE_STARS;
        }
        return TWO_STARS;
    }

I need to fill at table some enum values, as rating (2, 3, 4) and sleep places (1, 2..).

我需要在表中填写一些枚举值,如评级 (2, 3, 4) 和睡眠位置 (1, 2..)。

But this puts some wrong data into table.

但这会将一些错误的数据放入表中。

Here is content at workbench:

以下是工作台的内容:

apartment

公寓

Why it puts only index, not as string or as enum.
How can I recovering this at desired value, in the future.

为什么它只放置索引,而不是字符串或枚举。
将来我如何以所需的价值恢复它。

Here is snippet from Apartment class:

这是公寓类的片段:

@Entity
@Table(name = "Apartments")
public class Apartment extends AbstractEntity implements Comparable<Apartment> {    
    private Integer id;
    private String roomName;
    private Double pricePerHour;
    private ApartmentState apartmentState;
    private StarRating rating;
    private SleepPlaces sleepPlaces;
    private Boolean active;

    public enum ApartmentState {
        FREE, REQUESTED, BOOKED, LIVED, CLEANING, PROCESSING
    }

    public enum StarRating {
        TWO_STARS("2 stars"), THREE_STARS("3 stars"), FOUR_STARS("4 stars"), FIVE_STARS("5 stars");

        private String description;

        private StarRating(String description) {
            this.description = description;
        }
        public String getDescription() {
            return description;
        }
    }

    public enum SleepPlaces {
        ONE_PLACE("1 person"), TWO_PLACES("2 persons"), THREE_PLACES("3 persons"), FOUR_PLACES("4 persons");

        private String count;

        private SleepPlaces(String count) {
            this.count = count;
        }
        public String getCount() {
            return count;
        }
    }

For me the best is to put enum as enum (possibly at MySql workbench) or as a string (and use name()and valueOf()from Enum class).

对我来说,最好是将 enum 作为 enum (可能在 MySql 工作台)或作为字符串(并使用name()valueOf()来自 Enum 类)。

But how to implement it with hibernate.

但是如何用hibernate来实现它。

How to solve this trouble?

如何解决这个烦恼?

采纳答案by Frederic Close

You can add following enumeration, to indicate you want the String representation to be persisted :

您可以添加以下枚举,以指示您希望保留字符串表示形式:

@Enumerated(EnumType.STRING)
private ApartmentState apartmentState;

回答by gipinani

Use this annotation at field level:

在字段级别使用此注释:

@Enumerated(EnumType.STRING)

回答by DrFlash

I also had to add

我还必须添加

@Embeddableto the java enum

@Embeddable到 java 枚举

@Embeddable
 public enum ApartmentState {
        FREE, REQUESTED, BOOKED, LIVED, CLEANING, PROCESSING
    }