I got an entity with a column state. States stored in the DB are active and inactive (and some more). I wrote myself an enum like the following
public enum State {
ACTIVE("active"), INACTIVE("inactive");
private String state;
private State(String state) {
this.state = state;
}
}
The entity looks like:
@Entity
@Table(name = "TEST_DB")
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID")
private Integer id;
@Enumerated(EnumType.STRING)
@Column(name = "STATE", nullable = false)
private Integer state;
// constructor, getter, setter
}
Unfortunately I get the following error message:
javax.ejb.EJBTransactionRolledbackException: Unknown name value [active] for enum class [state]
Is it possible to do a case-insensitive hibernate-mapping to an enum?
I was facing with similar problem and found simple answer.
You can do something like:
(you don't need for "write" in
@ColumnTransformer
- for me it's for back compatibility, because my rows only in lower case. Withoutwrite
Hibernate will write enum in same case, as in code in enum constant)You can map an enum as an ORDINAL or a STRING with hibernate annotations, for example:
The ordinal mapping puts the ordinal position of the enum in the database. If you change the order of the enum values in your code this will conflict with existing database state. The string mapping puts the upper case name of the enum in the database. If you rename an enum value, you get the same problem.
If you want to define a custom mapping (like your code above) you can create an implementation of
org.hibernate.usertype.UserType
which explicitly maps the enum.First I suggest some changes to your enum to make what follows possible:
And here is a simple (!) implementation of UserType:
Then the mapping would become:
For another example of how to implement UserType, see: http://www.gabiaxel.com/2011/01/better-enum-mapping-with-hibernate.html