Why Do I Need Transaction in Hibernate for Read-Only Operations

Why do I need Transaction in Hibernate for read-only operations?

Transactions for reading might look indeed strange and often people don't mark methods for transactions in this case. But JDBC will create transaction anyway, it's just it will be working in autocommit=true if different option wasn't set explicitly. But there are practical reasons to mark transactions read-only:

Impact on databases

  1. Read-only flag may let DBMS optimize such transactions or those running in parallel.
  2. Having a transaction that spans multiple SELECT statements guarantees proper Isolation for levels starting from Repeatable Read or Snapshot (e.g. see PostgreSQL's Repeatable Read). Otherwise 2 SELECT statements could see inconsistent picture if another transaction commits in parallel. This isn't relevant when using Read Committed.

Impact on ORM

  1. ORM may cause unpredictable results if you don't begin/finish transactions explicitly. E.g. Hibernate will open transaction before the 1st statement, but it won't finish it. So connection will be returned to the Connection Pool with an unfinished transaction. What happens then? JDBC keeps silence, thus this is implementation specific: MySQL, PostgreSQL drivers roll back such transaction, Oracle commits it. Note that this can also be configured on Connection Pool level, e.g. C3P0 gives you such an option, rollback by default.
  2. Spring sets the FlushMode=MANUAL in case of read-only transactions, which leads to other optimizations like no need for dirty checks. This could lead to huge performance gain depending on how many objects you loaded.

Impact on architecture & clean code

There is no guarantee that your method doesn't write into the database. If you mark method as @Transactional(readonly=true), you'll dictate whether it's actually possible to write into DB in scope of this transaction. If your architecture is cumbersome and some team members may choose to put modification query where it's not expected, this flag will point you to the problematic place.

is hibernate @Transactional(readOnly=true) on read query a bad practice?

This is a good optimization practice. You can find the examples in the Spring Data documentation. And you won't need to annotate your whole service with @Transactional annotation because "..CRUD methods of the Spring Data JPA repository implementation are already annotated with @Transactional"
Getting started with Spring Data JPA

What is best practice for performing read only operations in JPA/Hibernate?

You have to understand that there is no definitive answer and everyone will give you different suggestions/advice based on their experience.

Generally, the preferred solution is to use a DTO approach, but how you implement that is left as an exercise for the developer. Some developers are too lazy or simply accept/cope with the possible negative effects of using entity queries. It really depends on your use case and your needs.

I think though, that what you are looking for is a solution like Blaze-Persistence Entity Views.

I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.

A DTO model for an example use case could look like the following with Blaze-Persistence Entity-Views:

@EntityView(User.class)
public interface UserDto {
@IdMapping
Long getId();
String getName();
Set<RoleDto> getRoles();

@EntityView(Role.class)
interface RoleDto {
@IdMapping
Long getId();
String getName();
}
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.

UserDto a = entityViewManager.find(entityManager, UserDto.class, id);

The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<UserDto> findAll(Pageable pageable);

The best part is, it will only fetch the state that is actually necessary!

Working of hibernate. Is it necessary to use transaction every time? Will it cause any issue if i dont use it while retieving data?

No, you don't need to use transaction unless and until you are planning to persist the data inside the db. And In your question you are not persisting the date you are just fetching the records from the db. So here not mandatory to use transaction.

Do you need a database transaction for reading data?

All database statements are executed within the context of a physical transaction, even when we don’t explicitly declare transaction boundaries (BEGIN/COMMIT/ROLLBACK).

If you don't declare transaction boundaries, then each statement will have to be executed in a separate transaction (autocommit mode). This may even lead to opening and closing one connection per statement unless your environment can deal with connection-per-thread binding.

Declaring a service as @Transactional will give you one connection for the whole transaction duration, and all statements will use that single isolation connection. This is way better than not using explicit transactions in the first place.

On large applications, you may have many concurrent requests, and reducing database connection acquisition request rate will definitely improve your overall application performance.

JPA doesn't enforce transactions on read operations. Only writes end up throwing a TransactionRequiredException in case you forget to start a transactional context. Nevertheless, it's always better to declare transaction boundaries even for read-only transactions (in Spring @Transactional allows you to mark read-only transactions, which has a great performance benefit).

Now, if you use declarative transaction boundaries (e.g. @Transactional), you need to make sure that the database connection acquisition is delayed until there is a JDBC statement to be executed. In JTA, this is the default behavior. When using RESOURCE_LOCAL, you need to set the hibernate.connection.provider_disables_autocommit configuration property and make sure that the underlying connection pool is set to disable the auto-commit mode.

@transactional(readonly = true) Vs @transaction in Hibernate

It’s only a hint.the readOnly parameter doesn’t guarantee its behaviour, is only a hint that may or may not be taken into account.Source

This just serves as a hint for the actual transaction subsystem; it will not necessarily cause failure of write access attempts. A transaction manager which cannot interpret the read-only hint will not throw an exception when asked for a read-only transaction but rather silently ignore the hint.

it’s closely related to the propagation setting. For example: for SUPPORT, readOnly flag won’t ever be used; for REQUIRES_NEW always; for REQUIRED it depends on whether we already are in the transactional context or not, etc.



Related Topics



Leave a reply



Submit