简体   繁体   中英

How can I get an OptimsticLockException instead of a StaleObjectStateException in Hibernate 4?

The desire is to catch OLE instead of SOSE to be less tightly coupled to hibernate in case we ever needed to change JPA providers.

The case that is producing the exception is very straightforward; i've breakpointed just before a versioned entity update is committed, committed a change directly in the db, and then allowed execution to continue.

It looks like from StaleObjectStateException vs OptimisticLockException that the answer should just be "use JPA annotations", but we are doing that. Specifically, the Entity in question imports annotations only from javax.persistence.*

It turns out this was because we were using hibernate Session objects rather than EntityManagers - Hibernate doesn't check for JPA annotations (and wrap SOSEs in OLEs if they are present) unless an EntityManager is being used.

We can't fix it because DropWizard uses Sessions, but now that we understand why this is happening and that it will happen consistently, we can just catch the SOSE and the issue is resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM