GionJh GionJh - 1 month ago 11
Java Question

How does JPA @Version annotation works when you have multiple entities

Suppose we are using a DB with isolation level set to: read_committed
and we are also using JPA Entities annotated with

@Version
.

We have two transactions T and K like these:

T ------------------------------------- K

start

read A

read B

read C

-------------------------------------- start

-------------------------------------- update A

-------------------------------------- end

update C

using the states of

object A and B

end

At this point in transaction T the update of C is successful, (version check is fine), so we are updating C using a status that never really existed on the
DB.

What's wrong with my understanding ?

Answer

Optimistic locking works for individual table rows only. In this particular case, the entity C can be updated successfully since the second transaction does not modify C.

If you want to create a conflict here, then you must use either of the following optimistic lock requests:

in the second transaction so that when you update the entity A, you also trigger a version increment in C.

Check out this article for more details.