How can we set the Read Uncommitted isolation level with JPA and Hibernate?

5.2k views Asked by At

In he famous book "Java persistence with Hibernate" we can read the following:

"A persistence context is a cache of persistent entity instances.... Automatic dirty checking is one of the benefits of this caching. Another benefit is repeatable read for entities and the performance advantage of a unit of work-scoped cache... You don’t have to do anything special to enable the persistence context cache. It’s always on and, for the reasons shown, can’t be turned off.

Does this mean that one can never achieve a transaction isolation level "Read uncommitted" with Hibernate?

2

There are 2 answers

0
Vlad Mihalcea On BEST ANSWER

Does this mean that one can never achieve a transaction isolation level "Read uncommitted" with Hibernate?

No, it doesn't. Hibernate offers application-level repeatable reads for entities. That's different than DB-level repeatable reads which applies to any query.

So, if you want a custom isolation level, like REPEATABLE_READ for all the queries executed by a given transaction, not just for fetching entities, then you can set it like this:

@Transactional(isolation = Isolation.REPEATABLE_READ)
public void orderProduct(Long productId) {  
    ...
}     

Now, your question title says:

(How) can we achieve isolation level Read Uncommitted with Hibernate / JPA?

If you are using Oracle and PostgreSQL, you cannot do that since Read Uncommitted is not supported, and you'll get READ_COMMITTED instead.

For SQL Server and MySQL, set it like this:

@Transactional(isolation = Isolation.READ_UNCOMMITTED)
0
Alex Mi On

Indeed, hibernate does offer repeateble reads thorugh its first-level cache (Persistence Context) as cited in the book

"Transactions and concurrency control" by Vlad Mihalcea.

as follows:

Some ORM frameworks (e.g. JPA/Hibernate) offer application-level repeatable reads. The first snapshot of any retrieved entity is cached in the currently running Persistence Context. Any successive query returning the same database row is going to use the very same object that was previously cached. This way, the fuzzy reads may be prevented even in Read Committed isolation level.

However, according to the same book above, it seems that using Spring with JPA / hibernate allows customizing the transaction isolation level.

In the book above we can also read the following:

Spring supports transaction-level isolation levels when using the JpaTransactionManager. For JTA transactions, the JtaTransactionManager follows the Java EE standard and disallows overriding the default isolation level. As a workaround, the Spring framework provides extension points, so the application developer can customize the default behavior and implement a mechanism to set isolation levels on a transaction basis.