views:

309

answers:

2

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

A: 

I don't think so. The second query in Thread-1 doesn't even hit the database, you'll get the (stale) object from the 1st level cache (the Session). But if you change the order after the second query, you'll get the exception when flushing the session.

Pascal Thivent
+1  A: 

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.

Manuel Darveau
Thanks for your answer. In the meantime i have written a test, which shows exactly what you have described.If thread-1 somehow changes the order before executing the second query, due to autoflush i will get the StaleObjectException.This actually happened in a recent project and seemed rather strange at first, because the change of the order was due to a sideeffect.