Hello. This post is somehow related to a previous one (
http://forum.hibernate.org/viewtopic.php?p=2384248)
The context: (running latest Hibernate stable version on Linux Sun's JDK 1.6, MySQL)
I have an UserAccount class that is extended by an AdminAccount class. Both are mapped to Hibernate, I use one table per class hierarchy.
The UserAccount has an unique constraint on the userName property.
For a certain operation I wish to transform an existing UserAccount object into an AdminAccount one.
What I tried so far:
* My first approach was to delete the old object prior to recreating the new one. The problem with that is that when I delete the old object, the session needs to be flushed at this point. If I don't flush it, when the transaction is commited Hibernate tries to insert the new object first and the DB complains that the unique constraint is violated - it is indeed as the new admin account object has the same userName as the older user account object which is to be deleted (unfortunately Hibernate schedules the object insertion before the object deletion).
Flushing the session when deleting the old object has proven to be a pain, as I want to be able to rollback my whole transaction if certain validations I perform go wrong. Thus this whole approach seems impossible to me, unless someone can advise me a better way.
* So my second approach was to try to update the original user account object. My code looks like (in Groovy):
def hibernateSession = sessionFactory.getCurrentSession()
UserAccount userAccount = UserAccount.get(id)
// In the following constructor most properties are copied
AdminAccount adminAccount = new AdminAccount(userAccount)
// Now copying id and version to the new object so that Hibernate thinks it is a detached object, not a transient one, and issue an UPDATE instead of an INSERT
adminAccount.id = userAccount.id
adminAccount.version = userAccount.version
// Evicting the previous object from the session
hibernateSession.evict(userAccount)
// Updating the object
hibernateSession.saveOrUpdate(adminAccount)
Unfortunately this also does not work. The object seems to be correctly updated in the DB, but its class stays an UserAccount (eg, in the SQL table, the column for the class discriminator did not have its value updated).
Why is this the case? I create an AdminAccount object, so Hibernate should know it is trying to update with an AdminAccount object... but maybe it somehow remembers that the row corresponded to an UserAccount before and thus issues the UPDATE without taking into account the new class...
I really need some insight into this problem. I have spent lots of hours googling and trying a lot of different things, so if someone can lend a hand it'll be really appreciated :)
Jean-Noel