본문 바로가기
IT/Spring

스프링 JPARepository JPQL 대신 native query 쓰기, 변수

by ZanyGeek 2022. 2. 4.

Spring Data 가 제공하는 @Query 주석을 통해 JPQL과 native SQL을 사용할 수 있다.

 

native query를 사용하고 싶으면, Repository 인터페이스에 아래의 예시처럼 하면 된다.

(Spring JPARepository 네이티브 쿼리를 통해 변수를 입력 하는 방법)

간단한 예시

@Query(value ="SELECT * FROM blogContent WHERE id = :contentId", nativeQuery = true)
BlogContent  findByContentId(@Param(value="contentId", Integer contentId);

사실 위의 예시는 메소드 명명 규칙에 따라 BlogContent findById(Integer id); 로 선언만 해주면 되지만, 쉬운 예시를 위해 사용했다.

nativeQuery = true 를 붙여주고, 변수에는 :변수명, 변수명을 @Param으로 처리 해주면 된다.

 

@Query JPQL, native SQL 학습을 위한 링크를 첨부한다.

스프링 데이터 JPA @Query

댓글