참치코더의 꿈 메모장

Spring / Projection 정리 (개인 프로젝트 부분 발췌) 본문

Spring

Spring / Projection 정리 (개인 프로젝트 부분 발췌)

참치깡 2025. 9. 24. 23:51
728x90

 

Spring Data JPA Projection

 

Projection

- 엔티티 전체가 아니라 일부 필드만 조회하고 싶을 때 사용

 

Interface-based Projection 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 인터페이스로 조회를 원하는 필드를 선택
// 인터페이스는 실체 클래스가 없고 getter만 정의된 인터페이스이다.
 
// 개인 프로젝트 발췌
 
public interface FindAllReservationDTO { 
    Long getId();
    String getCalender();
    String getClock();
    String getDogType();
    int getDogAge();
    String getName();
    String getPhone();
    String getLocation();
    int getDistance();
    String getEvent();
 
}
 
// Repository에서 사용
// Spring Data JPA가 쿼리를 실행하고 DB에서 가져온 컬럼을 자동으로 이 인터페이스의 getter와 매핑해 준다.
public interface reservationRepository extends CrudRepository<Reservation, Long> {
 
    @Override
    ArrayList<Reservation> findAll();
 
    List<FindAllReservationDTO> findAllProjectedBy();
}
 
 
 
// 컨트롤러 사용
// DB에서 엔티티 거치지 않고 바로 DTO로 변환 해서 출력한다.
// Entity를 만들지 않았다!!!
@GetMapping("/allReservation")
    public List<FindAllReservationDTOResponse> getAllReservation(){
        return reservationRepository.findAllProjectedBy()
                .stream()
                .map(p -> new FindAllReservationDTOResponse(
                        p.getId(), p.getCalender(), p.getClock(), p.getDogType(), p.getDogAge(),
                        p.getName(), p.getPhone(), p.getLocation(), p.getDistance(), p.getEvent()
                )).toList(); // password 제외후 춫력
    }
cs

 

장점

 

1. 쿼리 최적화

 - 엔티티 전체를 가져오지 않고, 필요한 컬럼만 SELECT 한다.

 

2. 코드 간결

- 인터페이스만 만들어두면 Spring이 알아서 자동으로 매핑해준다.

 

3. 읽기 전용 Projection

- 조회만 가능하고 수정용으로는 사용하지 않는다.

 

주의점

 

1. 인터페이스 Projection은 조회 전용

- @RequestBody로 받거나 엔티티 업데이트용으로 사용하면 안된다.

 

2. 컬럼 이름과 getter 이름 매핑

 - DB 컬럼명과 getter 이름이 맞아야 정상 작동 한다.

 

그 가장 중요한건 Entity를 만들지 않고 바로 DTO로 출력하는 것이 중요하다!!!

728x90
Comments