Mapping enum to string in hibernate

JavaHibernateEnums

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Yes, is possible. It should be:

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

Solution 2 - Java

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionducinView Question on Stackoverflow
Solution 1 - JavadcernahoschiView Answer on Stackoverflow
Solution 2 - JavaBraian CoronelView Answer on Stackoverflow