I have the same problem. I would like to use the State Pattern, in which each state is represented by a concrete subclass. My legacy database has a state column that holds integers representing the state. It would be very easy and elegant to implement a full State Pattern in Java and map it to the database like this:
Code:
<class name="Account" table="ACCOUNT">
<component name="state" class="AccountState" discriminator-value="null">
<discriminator column="STATE" type="integer"/>
<subclass name="AccountStateActive" discriminator-value="0" />
<subclass name="AccountStateInactive" discriminator-value="1" />
<subclass name="AccountStateCancelled" discriminator-value="2" />
</component>
...
Unfortunately, Hibernate does not (yet) support inheritance in the component tag. Hence I have 2 questions:
1) Can this feature be added to a future feature list? I think the prevalence of this type of State Pattern alone would warrent it, and it seems consistent with the overall design and use of the framework.
2) Does anyone have any recommendations about how to implement this without this feature? I have thought of several possibilities, all of them bad:
I thought of doing a one-to-one mapping of my AccountState class to the Account table, but I assume this will fail during inserts because, since they both point to the same table, the new AccountId will already be present when we try to insert the AccountState number (though I haven't tried this).
Another idea is to push the inheritance logic up into the domain model. That is, the stateId could be a simple integer mapped to the STATE column (which Hibernate can easily handle), and my setter for Account.stateId will handle the logic of finding and instantiating the correct subtype of AccountState. That's letting a lot of ugly persistence logic bleed into the domain model, but it should work.
A final possibility is to try to bastardize the UserType interface to treat the state as an immutable value type. That is, I could make an AccountStateUserType that is saved in the ACCOUNT table, and it uses the subtype to get the value and create the correct subclass when re-instantiating. Unfortunately, I don't see how this can work as the UserType method returnedClass() doesn't have any way to access the state number, which is needed to determine which subclass should be instantiated.
Am I missing something?
Thanks!
James