[JPA] Custom Query

keymu·2025년 1월 2일
0

JPA annotation +

@DynamicInsert

  • INSERT SQL을 생성할 때 null이 아닌 필드들만 포함
  • null 값을 가진 필드는 SQL문에서 제외되어, DB에 설정된 기본값(default value)이 적용
  • 생성일자(createdAt) 필드가 null이면 해당 필드는 INSERT 문에서 제외되고, DB에 설정된 기본값(예: CURRENT_TIMESTAMP)이 사용됨

@DynamicUpdate

  • UPDATE SQL을 생성할 때 변경된 필드들만 포함
  • 변경되지 않은 필드들은 UPDATE 문에서 제외
  • 불필요한 컬럼 업데이트를 방지하고 SQL 성능을 최적화

Custom Query를 사용하는 이유

1. Query Method의 가독성(너무 길어짐)

  • Query 구문은 SQL이 아닌 JPQL임.

JPQL

  • Entity 기반의 쿼리를 생성하기 위한 구문
  • (실제 생성된 물리적 테이블 이름: created_at) but, property명을 사용(createdAt)
  • dialect에 따라 쿼리 자동 생성
  • native query와 차이 있음

JPQL Positional Parameter

  • ?1, ?2...
  • 1-based index

JPQL Named Parameter

  • @Param ,: 접두어 사용
  • Parameter 순서에 영향 x

2. Entity 연결하지 않은 Query 사용 가능

// interface
public interface BookNameAndCategory1 {
   String getName();
   String getCategory();
}
// DTO
@Data
@AllArgsConstructor
@NoArgsConstructor
// 이는 엔티티가 아니다.
public class BookNameAndCategory2 {
   private String name;
   private String category;
}
@Test
void queryTest(){
   bookRepository.findBookNameAndCategory3().forEach(b -> {
       System.out.println(b.getName() + " : " + b.getCategory());
   });
}
profile
Junior Backend Developer

0개의 댓글