java – Transaction isolation level and Hibernate


First question . What is the relationship between the transaction isolation level, JPA Lock.READ / Lock.WRITE and @Version versions (Optimistic locking)? I more or less understood separately each of these 3 sections, but I do not understand how they are related to each other. The selected transaction isolation level provides some "guarantees" when performing operations with tables. The Lock.READ/Lock.WRITE parameters Lock.READ/Lock.WRITE you to lock table fields during operations. If I understood correctly, this is exactly what the @Version field is used for. But all the same, I do not fully grasp the connection between these three concepts. Either they complement each other, or they are different ways of solving the same problems. In general, I will be very grateful for an answer or a link where you can read information specifically on the connection between these concepts and their joint use.

Second question . How can you specify the required transaction isolation level for a particular transaction in Hibernate? And is it customary to do so?

Thank you.


I'll try to answer in order:

How Lock and Isolation Levels Relate

  1. Transaction isolation level – refers to reading data, but not writing data;
  2. Lock refers to data access (that is, it affects both reading and writing and modification);
  3. We can say that the Lock mechanism ensures the performance of various data isolation levels, in the most stupid example: if you have the READ_COMMITTED isolation READ_COMMITTED , then the insert made by the parallel session will be locked for writing until the session issues commit() , but the read lock will be open immediately at the request of your select , and at REPEATABLE_READ both locks (for reading and writing) will stand before commit() – accordingly, your select will see the modification results only after the commit.

How can you specify the required transaction isolation level for a particular transaction in Hibernate?

In general, this is not very great. The isolation level of transactions is the belonging of the connection to the database, respectively, in fact, changing the isolation level is tantamount to reconnecting to the database, and you yourself can estimate how expensive this operation is based on your current situation.

Nevertheless, if you do decide to change the transaction isolation level before each transaction, then the easiest way is to send a raw SQL query to the DBMS (any ORM supports this), such as:

Scroll to Top