Spring’s @Transactional(readOnly=true) to make it a read-only transaction

Spring’s @Transactional(readOnly=true) to make it a read-only transaction

Transactional annotation, but if readOnly=true, the transaction cannot be registered and updated. The default when omitted is readOnly=false.

The user table contains two data.

Spring's @Transactional(readOnly=true) to make it a read-only transaction


package jp.co.confrage.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jp.co.confrage.entity.UserEntity;
import jp.co.confrage.repository.UserRepository;
import lombok.RequiredArgsConstructor;

public class UserService {
  private final UserRepository repository;
   * read-only method
  @Transactional(readOnly = true)
  public void update() {
    UserEntity entity = repository.findById(1L).orElse(null);

    repository.save(entity); // No updates and no exceptions

The update method above updates the data, but the save method does not actually update the data and does not raise an exception.

If readOnly=false or omitted, it will update correctly.