220916 Native query에서 변수 받아오기

Jongleee·2022년 9월 16일
1

TIL

목록 보기
55/576

JPA에서 Native query를 쓸때는 아래와 같이 작성한다.

@Query(value = "SELECT * FROM concentration c where (c.member_id = :memberId) and (c.concentration_start_date like :date%)", nativeQuery = true)
List<Concentration> findAllByMemberAndStartDate(@Param("memberId") Long memberId, @Param("date") String date);

@param을 통해 받아온 값을 쿼리로 넘기고 @param에서 선언한 변수명의 앞에 :를 붙여서 쿼리 내에서 사용함

넘기고 싶은 파라미터가 많아지면 @Param을 갯수만큼 써줘야 함

@Query(value = "SELECT * FROM concentration c where (c.member_id = :#{#entity.memberId}) and (c.concentration_start_date like :#{#entity.date}%)", nativeQuery = true)
List<Concentration> findAllByMemberAndStartDate(@Param("entity") Entity data);
}

많은 파라미터를 넘겨야 하는 경우에는 엔티티 자체를 넘겨서 #{#param명.컬럼명}의 형태로 사용할 수 있다

0개의 댓글