em.getReference(), em.find() 호출 순서에 따른 결과 차이

선종우·2023년 6월 12일
0

실험실

목록 보기
1/4

1. find()메소드를 먼저 호출한 경우

  • 예제코드
Optional<Article> article = articleRepository.findById(commentDto.getArticleId());
Optional<Article> article2 = articleRepository.getReferenceById(commentDto.getArticleId());

System.out.println("article.get().getClass() = " + article.get().getClass());
System.out.println("article2.get().getClass() = " + article2.get().getClass());
  • 결과
    • find메소드를 호출한 경우 entity가 1차 캐시에 저장되며, 이후 getReference()를 호출하면 1차 캐시에 있는 entity를 그냥 가져온다.
article.get().getClass() = class com.jscode.demoApp.domain.Article
article2.get().getClass() = class com.jscode.demoApp.domain.Article

2. getReference()를 먼저 호출한 경우

  • 예제코드
Optional<Article> article = articleRepository.getReferenceById(commentDto.getArticleId());
Optional<Article> article2 = articleRepository.findById(commentDto.getArticleId());

System.out.println("article.get().getClass() = " + article.get().getClass());
System.out.println("article2.get().getClass() = " + article2.get().getClass());
  • 결과
    • getReference()를 이용해 이미 프록시 객체가 1차캐시에 있을 때는 뒤이어 find()를 호출하더라도 프록시객체를 반환한다.
article.get().getClass() = class com.jscode.demoApp.domain.Article$HibernateProxy$HDIjPHfh
article2.get().getClass() = class com.jscode.demoApp.domain.Article$HibernateProxy$HDIjPHfh

0개의 댓글