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

readOnly=trueにして、サービスクラスでパスワードを変更してみます。

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;

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

    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.

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL