Skip to content

Spring JPA getOne() vs findById()

Seong JaeHo edited this page Apr 6, 2020 · 3 revisions

오늘 기본에 구현해놓은 Repository를 인터페이스를 사용하는 Repository로 변경하는 작업중에 findOne이라는 메소드가 당연히 있는 줄 알았지만 아무리 찾아봐도 없어서 공식문서 + 블로그를 탐색하던 중 PK(Id)를 사용하여 검색하는 메소드를 찾아보았는데, 다음과 같이 2가지가 나옴

getOne(ID id) | findById(ID id)

둘 다 ID를 param으로 받음

처음 봤을 때 '둘 다 같은 의미 아님?' 이라 생각했으나 나눠놓은 이유가 있겠다 싶어 공식문서와 블로그를 다시 들여다 보았다.


T getOne(ID id)

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 EntityNotFoundException on first access. Some of them will reject invalid identifiers immediately.

Parameters:
id - must not be null.

Returns:
a reference to the entity with the given identifier.

See Also:
EntityManager#getReference(Class, Object) for details on when an exception is thrown.


T getReference(Class entityClass, Object primaryKey)

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

Parameters:
entityClass - entity class
primaryKey - primary key

Returns:
the found entity instance

Throws:
IllegalArgumentException - if the first argument does not denote an entity type or the second argument is not a valid type for that entity's primary key or is null
EntityNotFoundException - if the entity state cannot be accessed


Optional findById(ID id)

Retrieves an entity by its id.

Parameters:
id - must not be null.

Returns:
the entity with the given id or Optional#empty() if none found.

Throws:
IllegalArgumentException - if id is null.


요약

구분 getOne() findById()
Loading 방식 Lazy-loading Eager-loading
Returns Entity Reference or EntityNotFoundException Entity or null
Performance

언제 뭘 써야함?

  • getOne() - 객체의 속성에 접근할 필요가 없을 때(User에서 User가 가지고 있는 Category에 접근할 필요가 없을 때)

  • findById() - 객체의 모든 속성에 접근할 필요가 있을 때(User에서 Category에 접근할 필요가 있을 때)

  • 문득 궁금해서 찾아본 것 em.getReference vs em.find


JpaRepository Reference

CrudRepository Reference

Blog Reference 1

Blog Reference 2

Clone this wiki locally