I was mapping a Java 5 enum to a database column in a JPA-annotated Hibernate class today and almost created a UserType (ugh!). Then I remembered that it’s much easier! You can just use @Enumerated to convert between the enum’s toString() and a text (varchar, text, etc.) column transparently. There’s also support for more complex types which I have not had a chance to explore. The usage looks like this:
@Entity
public class MyClass {
...
@Enumerated(EnumType.STRING)
private MyEnum myCol;
...
}
See the JPA docs for a full example.
#1 by Andrew Swan on February 17, 2010 - 2:31 am
According to http://stackoverflow.com/questions/352586/how-to-use-enums-with-jpa, it uses Enum#name(), not Enum#toString(), which return the same thing by default but not necessarily.