[Spring Data JPA] getById vs findById

스브코·2022년 3월 19일
0

JPA를 사용하다 보면 요청에 따른 조회기능을 많이 구현하게 되는데 getById와 findById라는 두개의 유사한 메소드에 대해 한번 정리를 해보기로 했다.

Spring 공식 문서를 보면 두 메소드는 다음과 같이 정의 되어 있다.



T getById(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.


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.



같은 점

  • 둘 다 ID를 받아와서 Entity 객체를 리턴 해준다.

  • id가 null이면 안된다.

다른 점

  • findById의 리턴 타입은 Optional, getById의 리턴 타입은 T

  • ID로 조회한 Entity가 없을때, getById는 EntityNotFoundException, findById는 Optional.empty()를 리턴



내부 동작의 차이

GetById

getById는 원래 getOne이라는 메소드가 deprecated되면서 대체된 메소드이다.

이 메소드는 데이터베이스에 충돌하지 않고 항상 Lazy지연로딩으로 가져오는 프록시를 반환한다.

findById

이 메소드는 실제로 데이터베이스에 도달해 곧바로 매핑된 데이터를 리턴한다. Eager방식의 로드이기 때문에 데이터가 없다면 바로 null을 리턴하게 된다.

스프링에서 Entity 설계시 연관관계 설정은 예측하기 어려운 Eager로딩 설계보다는 Lazy로딩으로 설계하는것을 지향한다. 따라서, ID값으로 조회 시 엔티티가 존재가 보장된다면, getById로 엔티티를 조회하는것이 더 바람직하고, ID값이 확실히 존재하는지 불분명하다면 findById를 사용하여 존재여부를 확인하는 하면 될 것같다.



결론

하지만 존재여부를 확인하는것도 existById를 만들 수 있기때문에 나는 존재여부의 확인의 경우에는 existById와 확실한 엔티티 존재 보장을 동반한 조회의 경우는 getById, 존재확인 후 무조건 엔티티를 사용한다면 findById로 사용하는게 좋을것 같다.

existById의 동작 원리와 분석은 이 글에 자세히 나와있다.




참고 자료:

https://bcp0109.tistory.com/325
https://granger.tistory.com/50

profile
익히는 속도가 까먹는 속도를 추월하는 그날까지...

0개의 댓글