Performance: Read-only transactions
Read-only transactions reduce database locking and improve query performance, impacting server response time and user experience.
Jump into concepts and practice - no test required
@Transactional(readOnly = true)
public List<User> getUsers() {
return userRepository.findAll();
}@Transactional
public List<User> getUsers() {
return userRepository.findAll();
}| Pattern | Database Locks | Transaction Overhead | Query Speed | Verdict |
|---|---|---|---|---|
| Read-write transaction for read-only query | High locks | Higher overhead | Slower | [X] Bad |
| Read-only transaction for read-only query | Minimal locks | Lower overhead | Faster | [OK] Good |
@Transactional(readOnly = true) in Spring Boot?readOnly = true inside the @Transactional annotation.@Transactional(readOnly = true)
public List<User> getUsers() {
userRepository.save(new User("John"));
return userRepository.findAll();
}
What will happen when this method runs?save inside a read-only transaction causes Spring or the database to throw an exception.@Transactional(readOnly = true)
public void updateUserName(Long id, String name) {
User user = userRepository.findById(id).orElseThrow();
user.setName(name);
}
Why might this method fail to update the user's name?@Transactional(readOnly = true) explicitly marks the method as read-only, enabling optimizations and preventing writes.