Why you should not map Java 5 enums with hibernate

Back in this post, I gave some pretty detailed instructions on how to map a Java 5 enum to a database table using Hibernate. The domain data that was represented in these mappings were not user-editable. They were something like types or statuses, a part of the logic of the application. If one of these changed, it would affect the way the app worked, and many code changes would have to be made. These mappings did not contain data that the user would alter or update, for example a “topic” for a weblog app.

After using the approach of mapping enums with hibernate in this fashion in a professional project for the past few months, I would like to share these reasons why I would not take this approach again.

There is no real direct mapping from the enum to the database.

The map is only a type definition, which doesn’t provide column names for attributes to map to. If you were to change a column name in a standard hibernate mapping, you would only need to change the hibernate mappings that used that column, but with this pattern, you would actually need to go into your enum class and update the data within it. This goes against much of the Hibernate mindset I’ve seen.

The GenericEnumUserType is confusing.

How are you going to explain to new developers that come onto your team what is going on here, especially if they have no experience with Hibernate? Simplicity first, please.

No support for tracking metrics.

What if the requirement is not as simple as my first example? What if you are assigning a Person row a certain status, and you are required to keep track not only of the present status, but all past statuses, what user changed the status, and the timestamp of the assignment? A simple one-to-many mapping from a domain object FK’ed to a status table doesn’t cut the mustard anymore, because you need an association table between them that tracks metrics. And now you’ve got enough complexity in this model that it isn’t worth it.

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted November 9, 2008 at 7:00 am | Permalink

    This blog post draft has been sitting for almost a year now without me touching it. I’m just going to publish it because I hate throwing it away.

    I’ve moved on to Grails now anyway :), so all I have to worry about is the ordinal vs. string persistence issue (until 1.0.4 comes out, that is).

  2. Posted November 9, 2008 at 12:52 pm | Permalink

    @EnumType has been part of JPA for years, you should not have needed Grails anyway :)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*
Check out the latest GroovyMag to see an interview with me about the 1.1 release of GrailsUI: