[2025-02-24] Bean 생명주기, API 예외처리, JPQL & Fetch Join

이규정·2025년 2월 24일

📌 개요

Spring Bean의 생명 주기를 학습하고, 예외 처리를 전역적으로 관리하며, JPQL을 활용하여 데이터베이스를 효율적으로 다루는 방법을 배운다.


📌 목차

  1. 준비하기

    • Git clone
    • Bean 생명주기 개념
    • InitializingBean, DisposableBean 활용
  2. Bean 생명주기

    • Bean 속성
    • @PostConstruct, @PreDestroy
    • Bean Scope 종류 및 차이점
  3. API 예외 처리

    • @ExceptionHandler 활용
    • @ControllerAdvice & @RestControllerAdvice 비교
  4. JPQL 기본 개념

    • 문법 및 사용법
    • 반환 타입 및 결과
    • 파라미터 바인딩
  5. JPQL 응용

    • Embedded Type
    • Projection 활용
  6. 페이징(Paging)과 고급 JPQL

    • JOIN, CASE, 함수 활용
  7. Fetch Join

    • N+1 문제 해결
    • Entity Fetch Join & Collection Fetch Join
  8. Fetch Join 심화

    • @BatchSize 적용
    • 페이징 최적화
  9. Spring Data JPA & JPQL 적용

    • 실무 적용 사례
    • @PostConstruct 활용

📌 준비하기

✅ Git Clone

Git Clone은 원격 저장소(repository)의 전체 내용을 로컬 컨텐츠로 복사하는 Git 명령어이다.

git clone https://github.com/UK-spring/spring-callback

📌 Bean 생명주기

✅ Bean 생성과 관리

Spring은 Bean의 생성 → 주입 → 소멸까지 자동으로 관리한다.

  • 초기화 콜백: @PostConstruct, InitializingBean
  • 소멸 콜백: @PreDestroy, DisposableBean

✅ Bean Scope 종류

Scope설명
Singleton기본 설정 (Container 내 하나의 Bean만 생성)
Prototype매 요청마다 새로운 Bean 생성
RequestHTTP 요청당 Bean 생성
SessionHTTP 세션당 Bean 생성
Application서블릿 컨텍스트 내에서 하나의 인스턴스 생성

📌 API 예외 처리

✅ @ExceptionHandler

특정 Controller에서 발생하는 예외를 개별적으로 처리할 때 사용한다.

@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}

✅ @ControllerAdvice & @RestControllerAdvice

어노테이션설명
@ControllerAdvice모든 Controller의 예외를 공통 처리
@RestControllerAdviceJSON 응답을 반환하는 Controller의 예외 처리

📌 JPQL & Fetch Join

✅ Fetch Join (N+1 문제 해결)

  • N+1 문제 해결을 위해 Fetch Join을 활용할 수 있다.
  • Entity Fetch Join (단일 객체와 함께 조회)
    @Query("SELECT t FROM Tutor t JOIN FETCH t.company")
    List<Tutor> findAllWithCompany();
  • Collection Fetch Join (1:N 관계 객체를 함께 조회)
    @Query("SELECT c FROM Company c JOIN FETCH c.tutors")
    List<Company> findAllWithTutors();
    📌 주의: Fetch Join페이징과 함께 사용 불가!

✅ @BatchSize (페이징 지원 대안)

  • Fetch Join의 한계를 극복하기 위해 @BatchSize를 활용할 수 있다.
@BatchSize(size = 100)
@OneToMany(mappedBy = "company")
private List<Tutor> tutorList = new ArrayList<>();

📌 결론 및 정리

✔ Fetch Join은 N+1 문제를 해결하지만 페이징과 함께 사용할 수 없음 🚫
✔ @BatchSize를 활용하면 페이징과 Fetch 효과를 함께 적용 가능
✔ API 예외 처리는 @ExceptionHandler, @ControllerAdvice, @RestControllerAdvice를 적절히 조합하여 활용
✔ Spring Bean의 생명 주기를 잘 활용하면 효율적인 객체 관리가 가능 🚀

참고
https://teamsparta.notion.site/Spring-03e30571f1654107bb4364861ed01c1a

profile
반갑습니다. 백엔드 개발자가 되기 위해 노력중입니다.

0개의 댓글