Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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. I would like the Category model class to accept an enum variable - and map it somehow to the string whenever hibernate asks for it.

Is it possible?

like image 704
ducin Avatar asked Apr 13 '13 13:04

ducin


People also ask

How do I map an enum to a column in a database?

To map the Enum to a String database column type, you need to specify the EnumType. STRING value when using the @Enumerated annotation. As expected, the String representation of the Java Enum was used to populate the associated database column value.

How annotate enum in hibernate?

You can specify how the enum should be persisted in the database with the EnumType enum property of the @Enumerated annotation. EnumType. ORDINAL specifies that the enum will be persisted as an integer value. Here, myEnum set to VALUE1 would be persisted as 0, VALUE2 as 1, etc.

What is @enumerated in hibernate?

By default, Hibernate maps an enum to a number. It uses the ordinal value, which is the zero-based position of a value within the definition of the enum. So, the enum value that's defined first gets mapped to 0, the second one to 1 and so on.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


2 Answers

Yes, is possible. It should be:

@Enumerated(EnumType.STRING) @Column(name = "category_type") private CategoryType categoryType; 
like image 75
dcernahoschi Avatar answered Sep 24 '22 01:09

dcernahoschi


The accepted answer is not sufficient for PostgreSQL. I attach the implementation that worked for me:

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

like image 43
Braian Coronel Avatar answered Sep 24 '22 01:09

Braian Coronel