Mapping enum to string in hibernate

ducin picture ducin · Apr 13, 2013 · Viewed 59.6k times · Source

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?

Answer

dcernahoschi picture dcernahoschi · Apr 13, 2013

Yes, is possible. It should be:

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