Notice
Recent Posts
Recent Comments
Link
관리 메뉴

개발자되기 프로젝트

JPQL : 동적 parameter mapping 방법 본문

JPA

JPQL : 동적 parameter mapping 방법

Seung__ 2021. 7. 9. 21:45

JPQL : Java Persistence Query Language, table이 아닌 JPA Entity를 기반으로하는 query생성.
        따라서 createdAt의 경우 table의 created_at이 아니라 실제 field에서 사용한 이름을 사용했음.

 

query를 만들 때 static한 값 뿐 만 아니라 동적인 값도 필요하다.(ex. createdAt, updatedAt)

 

해당 동적 parameter를 query에 넣어주는 방법은 두 가지가 있다.

 

1. ????????????


?1, ?2, ?3, ?4 등등등 몇 번째 parameter를 넣을 것인가? 

간단하게 사용할 수 있지만, 만약 새로운 변수가 중간에 들어간다면 문제가 발생할 수 있다.

 

 

2. @Param


 가장 권장하는 방법! Parameter를 name기반으로 mapping

@Query(value = "select b from Book b "
+ "where name = :name and createdAt >= :createdAt and updatedAt >= :updatedAt")
List<Book> findByNameRecently(
  @Param("name") String name,
  @Param("createdAt") LocalDateTime createdAt,
  @Param("updatedAt") LocalDateTime updatedAt
  );

순서대로 parameter를  mapping하는 것이 아니기 때문에, 로직 변경에 의한 side effect가 적다.

 

 

'JPA' 카테고리의 다른 글

Transaction, @Transactional  (0) 2021.07.02
JPA/Hibernate 초기화(ddl-auto, initialization-mode 등)  (0) 2021.07.01
M : N(다대다) 연관관계 - 2  (0) 2021.06.22
M : N(다대다) 연관관계 - 1  (0) 2021.06.22
N : 1 연관관계 #2  (0) 2021.06.21
Comments