views:

420

answers:

1

I have an EnumSet that I thought it would be good to map into a series of boolean columns. This will make it easy to inspect using SQL tools and also resilient to changes to the available enum values. However, I don't really want to hand-write all the getters and setters for this.

Does anyone have a clever solution using some kind of hibernate metadata to split this object into a bunch of properties?

Thanks!

+1  A: 

If I understand you correctly, for an enum like:

public enum Color { RED, GREEN, BLUE; }

you would have 3 true/false columns in a database, one for each possible enum value. Then an EnumSet containing, say, RED and BLUE, should be mapped to:

RED    GREEN    BLUE
true   false    true

If that's the case, the only way I know of is to write your own implementation of org.hibernate.usertype.UserType. It's a pretty straight-forward task, with some examples available on Hibernate site and, for instance, here.

Edit: I just realized things would have to be somewhat more complex. If you wish to have one Hibernate type mapping for all possible EnumSet in your application, you will have to do the following:

  1. Use org.hibernate.usertype.ParameterizedType and make user type parameterizable by an enum class.
  2. Depending on values of enum class, determine how many and what columns to read/write.
  3. Instantiate the type each time an EnumSet is used.
  4. Consider the possibility of mapping multiple sets in one table, as well as how adding a new enum value will influence workings of existing type.

This could easily amount to full day's work, but seems quite doable. Hope you figure it out from here.

javashlook
Thanks ... I did it by hand but you provided what is probably the only solution.
Dobes Vandermeer