부트모아

[V1] 수정기능 구현시 쿼리수 줄이기

승무_ 2024. 9. 28. 14:40
public void updateArticle(ArticleDto dto) {
    Article article = articleRepository.findById(dto.id());
    article.setTitle("updated title");
    articleRepository.save(article);
}

맨 처음 게시글 제목을 수정하는 코드를 다음과 같이 작성하였는데, 로그를 확인해보니

 

Hibernate: select article0_.id as id1_0_0_, article0_.title as title2_0_0_ from article article0_ where article0_.id=?
Hibernate: insert into article (article_id, title) values (?, ?, ?)

select 쿼리, insert 쿼리 2개가 발생하는 것을 확인할 수 있었다.

 

그런데 좀 더 생각해보니, 이미 dto가 id를 알고있는데 db에서 조회하는 것이 반드시 필요한가라는 의문이 들었고, 관련된 자료를 찾아보다 getReferenceById를 알게 되었다.

 

getReferenceById는 내부적으로 EntityManager.getReference() 메소드를 호출하기 때문에 엔티티를 직접 반환하는게 아니라 프록시만 반환한다. 프록시만 반환하기 때문에 실제로 사용하기 전까지는 DB 에 접근하지 않으며, 만약 나중에 프록시에서 DB 에 접근하려고 할 때 데이터가 없다면 EntityNotFoundException 이 발생한다.

 

public void updateArticle(ArticleDto dto) {
    Article article = articleRepository.getReferenceById(dto.id());
    article.setTitle("updated title");
    articleRepository.save(artile);
}

다음과 같이 프록시를 이용해 수정 하였더니

Hibernate: insert into article (article_id, title) values (?, ?, ?)

select 쿼리가 사라지고 insert 쿼리만 발생하는 것을 확인할 수 있었다.

 

id 존재 여부가 확실한 경우는 쿼리의 수가 결국 비용이기 때문에 getReferenceById 쓰는 편이 좋을거 같다.