[TIL]230713 왜 create는 @Transactional 을 달지 않을까?

CountryGirl·2023년 7월 13일

TIL

목록 보기
24/80

JpaRepository를 사용해서 CRUD를 만들었다.

create, read, update, delete를 하면서
create는 save(), read는 findById(), delete는 delete() 라는 JpaRepository의 메서드를 사용해서 구현을 하였다.

CRUD

// create
public PostResponseDto createPost (PostRequestDto postRequestDto) {
        Post post = new Post(postRequestDto);
        postRepository.save(post);
        return new PostResponseDto(post);
    }
    
    
// read (get)
public PostResponseDto getPost(Long id){
        Post post = new Post();
        Post findPost = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("존재하지 않습니다."));
        return new PostResponseDto(findPost);
    }
    
    
// delete
public DeleteResponseDto deletePost(Long id) {
        Post post = findPost(id);
        postRepository.delete(post);
        return new DeleteResponseDto();
    }

update는 생성자로 만들어주었다.

// update
@Transactional
    public PostResponseDto updatePost(Long id, PostRequestDto postRequestDto) {
        Post post = findPost(id);
        post.update(postRequestDto);
        return new PostResponseDto(post);
    }
    
// Post 생성자
public void update(PostRequestDto postRequestDto) {
        this.title = postRequestDto.getTitle();
        this.username = postRequestDto.getUsername();
        this.contents = postRequestDto.getContents();
    }

이런 식으로 구현을 하였다. update@Transactional Annotation 이 있고,
다른 메서드들은 @Transactional Annotation이 필요하지 않았다.

그래서 나는 단순히 Dirty Checking 을 하기 위해서 update만 @Transactional Annotation을 달아야하는 것인줄 알았다.....

하지만 아니었다.

그것도 맞지만,

read는 그냥 가져오는 것이어서 select 만 하면 되니까 필요가 없었던 것 같다.

create 사용한 save()에는 이미 @Transactional Annotation이 달려있었다..............

SimpleJpaRepository에서 save()를 보면 달려있다!!!!!

save()

유레카 !!!!!

너무 신기했다. 조금 궁금했던 것이 해결되어서 좋았다.

profile
💻🌾시골소녀의 엉망징창 개발 성장일지🌾💻 (2023.05.23 ~)

0개의 댓글