@Transactional(readOnly = true) 실제 오류 체험해보기

0

TIL

목록 보기
149/183

프로젝트를 진행하면서 팀원들간에 Service 클래스에 @Transactional(readOnly = true)를 사용하는 것이 어떻겠냐는 피드백이 나왔다.

https://velog.io/@lswoo0705/TransactionalreadOnly-true

예전에 Transactional에 대해 정리해둔 적이 있었기 때문에 호기심에 쓰기 호출에 대해 @Transactional 어노테이션을 붙이지 않고 호출을 해보았다.

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CategoryService {

    private final CategoryRepository categoryRepository;

//    @Transactional
    public void createCategory(CategoryCreateRequestDto categoryCreateRequestDto) {
        String categoryName = categoryCreateRequestDto.categoryName();
        if (categoryRepository.existsByCategoryName(categoryName)) {
            throw new CustomException(ErrorCode.DUPLICATED_CATEGORY);
        }

        Category category = new Category(categoryName);

        categoryRepository.save(category);
    }
}



api를 호출하니 201 Created가 나오면서 성공했다고는 표시되지만



DB에는 저장되어있지 않았고



다시 @Transactional 어노테이션을 활성화 시킨 후 api를 호출해보면

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CategoryService {

    private final CategoryRepository categoryRepository;

    @Transactional
    public void createCategory(CategoryCreateRequestDto categoryCreateRequestDto) {
        String categoryName = categoryCreateRequestDto.categoryName();
        if (categoryRepository.existsByCategoryName(categoryName)) {
            throw new CustomException(ErrorCode.DUPLICATED_CATEGORY);
        }

        Category category = new Category(categoryName);

        categoryRepository.save(category);
    }
}



성공적으로 쿼리문에 의해 값이 데이터에 저장되는 것을 확인할 수 있다.

0개의 댓글

관련 채용 정보