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?
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.
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.
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.
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.)
Yes, is possible. It should be:
@Enumerated(EnumType.STRING) @Column(name = "category_type") private CategoryType categoryType;
The accepted answer is not sufficient for PostgreSQL. I attach the implementation that worked for me:
https://stackoverflow.com/a/64021041/5279996
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With