Introduction
Read-only transactions tell the system you only want to look at data, not change it. This helps the system work faster and safer.
Jump into concepts and practice - no test required
Read-only transactions tell the system you only want to look at data, not change it. This helps the system work faster and safer.
@Transactional(readOnly = true)
public ReturnType methodName() {
// code that only reads data
}@Transactional(readOnly = true)
public List<User> getAllUsers() {
return userRepository.findAll();
}@Transactional(readOnly = true)
public Optional<Product> findProductById(Long id) {
return productRepository.findById(id);
}This service class has a method to get all books. The method is marked as read-only transaction because it only reads data.
import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class BookService { private final BookRepository bookRepository; public BookService(BookRepository bookRepository) { this.bookRepository = bookRepository; } @Transactional(readOnly = true) public List<Book> getAllBooks() { return bookRepository.findAll(); } } // Assume BookRepository extends JpaRepository<Book, Long>
Read-only transactions can help databases optimize queries.
Do not try to save or update data inside a read-only transaction; it may cause errors or be ignored.
Use read-only transactions when you only need to read data.
Mark methods with @Transactional(readOnly = true) in Spring Boot.
This improves performance and prevents accidental data changes.
@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.