3logy
3logy

Reputation: 2712

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

I use Spring(Service Layer and Repository) to do CRUD operations on a mysql database.

MyServiceImpl :

@Service
@Transactional
public class MyServiceImpl implements MyService {
 private final MyRepository myrepo;
 ....

 @Transactional(readOnly = true)
 public Optional<myObj> findOne(Long id) {
    return myrepo.findById(id);
 }
}

is the using of readonly=true for read operations a bad practice? what about performance?

Upvotes: 2

Views: 8995

Answers (2)

Vasily Komarov
Vasily Komarov

Reputation: 1425

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

Upvotes: 3

MyTwoCents
MyTwoCents

Reputation: 7622

To start with, since Spring doesn't do persistence itself, so readonly is only a hint to the provider for behaviour(e.g Hibernate)

As per Hibernate's behavior readonly=true will set FlushMode.NEVER in current session which will prevent committing the transaction.

If you don't explicitly set readOnly to true, you will have read/write transactions.

Now coming Back to your Question

Looking at your findOne method. Looks like you are doing a Read call from database.

So its good to mark it as readonly to let your Provider know you are reading only.

You can read more in Detail here

https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/transaction.html

Spring @Transactional read-only propagation

Upvotes: 0

Related Questions