Search code examples
springspring-data-jpatransactional

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?


Solution

  • 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