TIL

findById vs getReferenceById

haedal-uni 2022. 12. 12. 01:28
728x90

스터디에서 getReferenceById()를 이용해서 작성했다고 하니

굳이 쓸 필요는 없고 findById()를 써도 될듯하다고 했다. 

그래서 getReferenceById()도 어디서는 분명히 쓸텐데 findById()만 쓰게 되면

getReferenceById()는 있을 필요가 없지 않을까 싶어서 좀 더 찾아보게 되었다.

 

* Git blog에도 정리했다. (내용이 더 많음)

 

getReferenceById()는 실제 테이블을 조회하는 대신 프록시 객체만 가져온다.

 

getIdx()를 호출하더라도 Registry를 SQL로 조회하지 않는다.

→  이 경우 쿼리가 발생하지 않는다.

 

Comment → Registry 가 LAZY 관계이면

Comment 테이블을 조회하는 시점에 registryId가 이미 FK로 Comment 테이블의 값에 포함되어 있다.

JPA는 이 값으로 Registry의 프록시 객체를 만들기 때문에 프록시 객체는 내부에 이미 registryId를 가지고 있다.

따라서 이 경우 registryId를 조회할 때는 프록시를 초기화 하지 않는다.

인프런

 

 

 

프록시 객체만 있는 경우 ID 값을 제외한 나머지 값을 사용하기 전까지는 실제 DB 에 액세스 하지 않기 때문에

SELECT 쿼리가 날아가지 않는다.

 

 

실제로 그런지 TEST해봤다.

 

public Comment setComment(CommentDto commentDto) {
    System.out.println("쀼뷰뷰뷰ㅠ븁");
    Registry registry = registryRepository.getReferenceById(commentDto.getRegistryIdx());
    System.out.println();
    
    
    System.out.println(" = = = = = = = = = = == = = = = = = = = = = ");
    System.out.println("findById");
    System.out.println(registryRepository.findById(commentDto.getRegistryIdx()));
    System.out.println();
    
    
    System.out.println(" = = = = = = = = = = == = = = = = = = = = = ");
    System.out.println();
    System.out.println("getReferenceById");
    System.out.println(registryRepository.getReferenceById(commentDto.getRegistryIdx()));
    System.out.println();
    System.out.println("  == = = = = = = = == = = = = =  끝 = = = = = = = == = = = =  ");
    
    Comment comment = commentDto.toEntity(registry);
    Comment save = commentRepository.save(comment);
    return save;
}

 

전체

 

 


    System.out.println("쀼뷰뷰뷰ㅠ븁");
    Registry registry = registryRepository.getReferenceById(commentDto.getRegistryIdx());
    System.out.println();

 

getReferenceById()를 사용하는 구문에서는 쿼리가 발생하지 않았다.

 

 

 

 

    System.out.println(" = = = = = = = = = = == = = = = = = = = = = ");
    System.out.println("findById");
    System.out.println(registryRepository.findById(commentDto.getRegistryIdx()));
    System.out.println();

 

findById()를 사용하니 select 쿼리가 떴다.

 

 

 

 

    System.out.println(" = = = = = = = = = = == = = = = = = = = = = ");
    System.out.println();
    System.out.println("getReferenceById");
    System.out.println(registryRepository.getReferenceById(commentDto.getRegistryIdx()));
    System.out.println();
    System.out.println("  == = = = = = = = == = = = = =  끝 = = = = = = = == = = = =  ");

 

 

 

getReferenceById()를 사용하니 실제로 SELECT 쿼리가 날아가지 않는다.

실제 DB 에 접근하냐 하지 않냐는 성능에 영향이 갈 수도 있으니 지금같은 경우에서는 find대신 get을 써야겠다.

https://bcp0109.tistory.com/325

 

 

728x90

'TIL' 카테고리의 다른 글

프로젝트 - 연관관계 매핑 끝  (0) 2022.12.20
이 글도 공감해주세요 refactoring  (0) 2022.12.13
가설  (0) 2022.12.10
스터디 요약  (0) 2022.12.04
프로젝트 관련 공부  (0) 2022.12.03