132

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?

0

3 Answers 3

248

Yes, is possible. It should be:

@Enumerated(EnumType.STRING)
@Column(name = "category_type")
private CategoryType categoryType;
Sign up to request clarification or add additional context in comments.

6 Comments

You can even go further and, now as JPA 2.1 is released, use @Converter(autoApply = true) public class CategoryTypeConverter implements javax.persistence.AttributeConverter <CategoryType, String>
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; }.
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.
See stackoverflow.com/questions/44864675/… if your enumeration value is being written as ordinal despite Enumerated annotation.
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?
|
5

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

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

Comments

0

I had to add

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

to @dcernahoschi solutions to make it work.

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

Without I got the Exception

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "

1 Comment

Thanks Patrick. Otherwise there is no need to use two @Column annotations. It's does not work. use just one: @Column(name = "category_type", columnDefinition = "VARCHAR(30)").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.