简体   繁体   English

将枚举映射到休眠中的字符串

[英]Mapping enum to string in hibernate

I've got a Category Hibernate model:我有一个类别休眠模型:

@Entity
@Table(name = "category")
public class Category {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "type")
    private String type;

which have a type string field.其中有一个类型字符串字段。 Also I've got a Java enum which represent a type of a category:另外,我有一个代表类别类型的 Java 枚举:

public enum CategoryType {
    INCOME, OUTCOME;
}

which I would like to use instead of the string type.我想使用它而不是字符串类型。 The SQL accepts two distinct values in the varchar parameter: either CategoryIncome or CategoryOutcome . SQL 在 varchar 参数中接受两个不同的值: CategoryIncomeCategoryOutcome I would like the Category model class to accept an enum variable - and map it somehow to the string whenever hibernate asks for it.我希望 Category 模型类接受一个枚举变量 - 并在 hibernate 要求它时以某种方式将其映射到字符串。

Is it possible?是否有可能?

Yes, is possible.是的,有可能。 It should be:它应该是:

@Enumerated(EnumType.STRING)
@Column(name = "category_type")
private CategoryType categoryType;

The accepted answer is not sufficient for PostgreSQL .接受的答案对于PostgreSQL是不够的。 I attach the implementation that worked for me:我附上了对我有用的实现:

https://stackoverflow.com/a/64021041/5279996 https://stackoverflow.com/a/64021041/5279996

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM