Tuesday, July 27, 2010

jPitfalls - Enums in Hibernate

In Hibernate you have two ways defining the association between database fields and Java properties. You can use xml definitions or Annotations.

I for example started with xml and later changed everything to Annotations. Either way, i used jBoss Hibernate Tools in Eclipse for generating the Java Class Files and xml Configuration.

Fortunately both Database and Java have Enums. Unfortunately the Hibernate Tool does not. (don't get me started on Hibernate at this point) So while you may think "Hey, i used Enums in my Database Design because i am a genius" and "That's great, now i can use them in Java" you can't. (Who is the genius).

Using Annotations it's easier. Creating Enums, adding them into the Hibernate Class Files and voila, you have Enums. (But don't forget to maintain them = meaning if you change the Enum in Java or the Database you have to change the other Part two by hand).

Using xml is a complete different Story. You have to Define the Type and adjust it by Hand. There is even a GenericEnumUserType explained in the jBoss Community.

In the end i still think that it should also be possible to create Enums automatically and some day it might, but in the meantime stay sharp and check you Enums.

Linktipps:
http://community.jboss.org/wiki/Java5EnumUserType
http://weblog.dangertree.net/2007/09/23/mapping-java-5-enums-with-hibernate/

No comments: