čtvrtek 11. března 2010

JPA: Mapping from Enum to Char(1)

Very often, enumerations are stored in SQL databases as char(1) columns. However, JPA annotation Enumerated allows mapping from Java Enum type into javax.persistence.EnumType.STRING (i.e. SQL type VARCHAR) or javax.persistence.EnumType.ORDINAL (i.e. SQL type INTERGER) only.

I have read a few rather complicated advices, how to make a mapping from general Java Enum type into SQL char(1) in Hibernate. After a while, I have found out, that when all constant names in the Enum have length just character, one can make an easy JPA mapping:
@Basic(optional = false)
@Enumerated(EnumType.STRING)
@Column(nullable = false, columnDefinition = "char(1) default 'A'")
private FruitType fruit_type = FruitType.A;
So, the FruitType may be:
public enum FruitType {
  /** Apples */
  A,
  /** Apricots */
  B,
  /** Cherries */
  C,
  /** Pears */
  P;
}

Well, it has a disadvantage, that "apricots" are represented by FruitType.B. But all modern IDE (like Eclipse) shows Javadoc when the developer types the code. Beside the simplicity, the other great advantage is, that the application developer knows that the "apricots" are represented by 'B' in the database. So, it is easier for the developer to write JPQL/HQL/SQL queries. When you a complicated JPA/Hibernate mapping from some type FruitTypeLong.APPRICOT to the 'B' in database, then it will be just confusing after some time to write JPQL/HQL/SQL queries.

1 komentář:

Anonymní řekl(a)...
Tento komentář byl odstraněn administrátorem blogu.