2

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?

3logy
  • 2,634
  • 8
  • 46
  • 99
  • Why would it be? It's actually a good practice, as it allows optimisation by the ORM. – sp00m Jul 25 '18 at 08:33
  • He's probably referring to this: https://stackoverflow.com/questions/34797480/why-do-spring-hibernate-read-only-database-transactions-run-slower-than-read-wri – Robert Niestroj Jul 25 '18 at 08:49

2 Answers2

3

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

Vasily Komarov
  • 1,405
  • 9
  • 11
0

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

MyTwoCents
  • 7,284
  • 3
  • 24
  • 52