javahibernateormoptimistic-concurrencystaleobjectstate

Hibernate - StaleObjectStateException in query possible?


Is it possible to get a StaleObjectStateException with Hibernate when you do the same query twice inside one tx if the result data of that query gets changed by a concurrent update inside a different session between the first and the second query?

I am using optimistic concurrency control on all entities in this scenario.

So it looks like this.

Thread-1: Transaction begins
Thread-1: query gets executed and retrieves i.e order with key=4711
Thread-2: same order with key 4711 gets retrieved, changed and committed in second thread
Thread-1: query gets executed again and should return order with key=4711

Will I get a StaleObjectStateException in Thread-1 in the second query?

Thanks for your help!

Thomas


Solution

  • Disclaimer: I have not tried it, this is what is expect from what I know of hibernate.

    You will not get a StaleObjectStateException when executing the second query nor when the transaction from thread-1 is commited.

    However, if if the order was modified before the second query is executed, the order will get flushed (assuming auto-flush mode and read-write transaction) right before the second query gets executed and this will trigger a StaleObjectStateException.