Tuesday, November 22, 2011

Hibernate, ElementCollection, and Transactions

Hibernate implemented @ElementCollection in the JPA by binding the persistence of the ElementCollection of a new entity at the end of the transaction, and NOT at the time you tell the EntityManager to persist.  Under most use cases, this should not be a problem, however it does mean that you cannot detach the entity from the EntityManager prior to ending the Transaction.

For example, the following will not persist your ElementCollection.


You will likely not run into situations like this, however I'm posting as I ran into some code that I was refactoring for Spring 3.1.  3.1 did not like nested @Transactions on a particular thread, and in the code's original design, it was detaching the entity on the nested item to avoid conflicts, I removed the nested @Transaction but did not notice the detach, and spent days figuring out why hibernate was not persisting the collection.  The answer is, as stated above, hibernate does not persist the collection at .persist, but on commit.

1 comment:

  1. Adam,

    I hate to bug you, so delete or ignore this comment if need be. But I was impressed with the few posts on your blog and figured I'd reach out. If you're looking for a career change, or just something better, check out www.objectpartners.com, or better yet, check out http://www.objectpartners.com/careers/why-opi/ to see if you'd be interested. Again, don't want to be an annoying recruiter so reply only if interested.

    Happy new year, and go GOP! :)

    --Ehren Seim

    ReplyDelete