Search code examples
javahibernatejpatransactionsoptimistic-locking

StaleObjectStateException or OptimisticLockingException


where can I find information on what Exception to catch in a version based optimistic locking save operation.

Texts on "the internet" suggests any of either Hibernate's own or JPA's OptimisticLockingException, but as I went for that I see that in my Hibernate 4.3 Session based app this type of Exception comes carried by a org.hibernate.StaleObjectStateException.

The differences of the suggestions makes me wonder what the "real "way to do this is.

Also, I have prepared moving from Hibernate Session to JPA. Is there a standard on this issue (of mine)? What would that be?

Cheers Mats


Solution

  • It depends on the API you are going to use.

    1. If you use JPA and the EntityManager interface, then Hibernate will simply wrap the StaleStateException, which is a base class of StaleObjectStateException in anOptimisticLockingException.

    2. If you use the Hibernate-specific API through the Session interface, you'll get the StaleObjectStateException instead.