123

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?

GG.
  • 21,083
  • 14
  • 84
  • 130
ducin
  • 25,621
  • 41
  • 157
  • 256

3 Answers3

235

Yes, is possible. It should be:

@Enumerated(EnumType.STRING)
@Column(name = "category_type")
private CategoryType categoryType;
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
  • 19
    You can even go further and, now as JPA 2.1 is released, use `@Converter(autoApply = true) public class CategoryTypeConverter implements javax.persistence.AttributeConverter ` – membersound Apr 14 '14 at 12:48
  • 8
    For anyone who might have the same problem..: I had to put this annotation to my getter method instead of the field, like this: `@Enumerated(EnumType.STRING) public CategoryType getCategoryType() { return this.categoryType; }`. – ZeroOne Mar 18 '16 at 13:46
  • 1
    I was in `hibernate.ddl-auto=update` mode and I had to drop my table and let hibernate create it again in order to convert my enum from int to varchar. Hopefully it helps someone with similar issue. – Arashsoft Feb 15 '18 at 21:35
  • See https://stackoverflow.com/questions/44864675/hibernate-enumerated-seems-to-be-ignored if your enumeration value is being written as ordinal despite Enumerated annotation. – metamaker Dec 11 '18 at 01:55
  • I do not put it on the getter. Putting it on the variable declaration works fine, which is good for Lombok using @Data, etc. What if I want to apply this to all Enums without annotating each one? – Andrew Jul 26 '20 at 19:40
5

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

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

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
0

I had to add

@Column(columnDefinition = "VARCHAR(30)")

to @dcernahoschi solutions to make it work.

@Column(columnDefinition = "VARCHAR(30)")
@Enumerated(EnumType.STRING)
@Column(name = "category_type")
private CategoryType categoryType

Without I got the Exception

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "
Patrick
  • 21
  • 3