상세 컨텐츠

본문 제목

[JPA] getOne과 findById ID로 객체 조회하기

JAVA/SPRING

by ranlan 2021. 4. 14. 01:10

본문

728x90

Spring Data JPA를 사용하여 객체의 @Id로 조회할 때 두 메서드 모두 사용 가능하다. 그 차이점은 무엇일까?

 

getOne()

/**
  * Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is
  * implemented this is very likely to always return an instance and throw an
  * {@link javax.persistence.EntityNotFoundException} on first access. Some of them will reject invalid identifiers
  * immediately.
  *
  * @param id must not be {@literal null}.
  * @return a reference to the entity with the given identifier.
  * @see EntityManager#getReference(Class, Object) for details on when an exception is thrown.
*/
T getOne(ID id);

지연(Lazy)로딩으로 작동, 주어진 식별자를 가진 엔티티에 대한 참조를 반환하며 내부적으로 EntityManager.getReference() 메서드를 호출해 프록시 객체 반환

null체크는 의미 없으며 DB에 존재하지 않을 경우 EntityNotFoundException 을 발생

 

 

findById()

/**
  * Retrieves an entity by its id.
  *
  * @param id must not be {@literal null}.
  * @return the entity with the given id or {@literal Optional#empty()} if none found.
  * @throws IllegalArgumentException if {@literal id} is {@literal null}.
*/
Optional<T> findById(ID id);

즉시(Eager)로딩으로 작동하여 호출 시 DB를 조회하고 실제 엔티티를 반환

메서드의 반환값이 Optional로 내부에 객체가 있는지 확인 후 get()을 이용해 반환된 객체를 꺼내 쓸 수 있음

 

사용예시)

@Transactional(readOnly = true)
public Board findBoardByNo(Long boardNo) {
	
    return  boardRepository.findById(boardNo).orElseThrow(() -> new NoSuchElementException());
}

 

 

[참고] 2021.03.11 - [java/jpa] - [JPA 기초] 프록시와 지연로딩

 

[JPA 기초] 프록시와 지연로딩

객체 조회 시 해당 객체가 참조하는 객체의 정보도 한번에 모두 불러와야 하는가? ex) MEMBER 객체가 TEAM 객체를 참조할 때, MEMBER 조회 시 TEAM도 함께 조회해야 하는가? 이전 코드 Member member = new Membe

juran-devblog.tistory.com

getOne findById
Id(필수값)로 객체 조회
지연로딩 즉시로딩
프록시 객체 반환 데이터베이스 조회 후 객체 반환
EntityNotFoundException 예외 발생 Optional로 Null 체크 가능

 

728x90

'JAVA > SPRING' 카테고리의 다른 글

[SPRING SECURITY] CSRF  (0) 2021.04.16
[SPRING SECURITY] 커스텀 클래스와 로그인  (0) 2021.04.16
[ERROR] 순환참조 문제  (0) 2021.04.14
[WEB] RESTful API 만들기  (0) 2021.03.22
[JPA] 게시판 CRUD  (0) 2021.03.21

관련글 더보기

댓글 영역