JPA - getById() vs findById()

Bruce Han·2022년 9월 6일
1

ORM

목록 보기
1/1
post-thumbnail

getById()

  • 내부적으로 EntityManager의 getReference() 메서드를 호출하고, 프락시 객체를 반환받음

  • 실제 쿼리는 프락시 객체를 통해 최초로 데이터에 접근하는 시점에 실행됨. 이때 데이터가 존재하지 않는 경우에는 EntityNotFoundException이 발생함

SimpleJpaRepository의 getById() 메서드

@Override
public T getById(ID id) {
	Assert.notNull(id, ID_MUST_NOT_BE_NULL);
    return em.getReference(getDomainClass(), id);
}

findById()

  • 내부적으로 EntityManager의 find() 메서드를 호출하고, 이 find()는 영속성 컨텍스트의 캐시에서 값을 조회함

  • 만약 영속성 컨텍스트에 값이 존재하지 않는다면 실제 데이터베이스에서 데이터를 조회함

  • 반환 값으로 Optional 객체를 전달함

SimpleJpaRepository의 findById() 메서드

@Override
public Optional<T> findById(ID id) {
	Assert.notNull(id, ID_MUST_NOT_BE_NULL);
    
    Class<T> domainType = getDomainClass();
    
    if (metadata == null) {
    	return Optional.ofNullable(em.find(domainType), id));
    }
    
    LockModeType type = metadata.getLockModeType();
    
    Map<String, Object> hints = new HashMap<>();
    getQueryHints().withFetchGraphs(em).forEach(hints::put);
    
    return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
}    

어떤 메서드를 사용하면 좋을까?

사실 조회 기능을 구현하기 위해서는 어떤 메서드를 사용하든 상관없다

인 것으로 알고 있습니다만, 추가적인 의견 있으신 분은 알려주시면 압도적으로 감사드리겠습니다.🙇‍♂️

Reference

(책) 스프링부트 핵심 가이드 (지은이 - 장정우, 출판사 - 위키북스)

todo - Java Optional 정리, 프록시 정리
profile
만 가지 발차기를 한 번씩 연습하는 사람은 두렵지 않다. 내가 두려워 하는 사람은 한 가지 발차기를 만 번씩 연습하는 사람이다. - Bruce Lee

0개의 댓글