[Spring Boot] jpa에서 @query

이맑음·2021년 11월 26일
0

Spring Boot

목록 보기
21/21
post-thumbnail

@Column(columnDefinition) -> auto DDL시 사용하는 속성
columnDefinition은 sql 타입을 치환해줌
jpql -> @Query, jpa entity기반으로 쿼리를 생성

1) 숫자 기반의 파라미터 맵핑방법

@Query(value="select b from Book b where name=?1 and createdAt >= ?2 and updatedAt >= ?3 and category is null") -> 단순 string
List<Book> findByNameRecently(String name, LocalDateTime updatedAt, LocalDateTime createdAt)

-> ?1 = 1번째 파라미터 값을 치환해줌(1부터 시작)
-> 숫자로 맵핑하기 때문에 순서에 의존o
-> 자바에서는 순서에 의존하는 것을 기피함. 왜냐 언제 파라미터 값이 추가 될지 모르기 때문에

2) 이름 기반의 파라미터 맵핑 방법
파라미터 앞에 @param("value")를 지정해준다

@Query(value="select b from Book b where name= :name and createdAt >= ?2 and updatedAt >= ?3 and category is null") -> 단순 string
List<Book> findByNameRecently(@param("name")String name, LocalDateTime updatedAt, LocalDateTime createdAt)

@where()

@native Query
= 이름 그대로 디비에서 사용하는 sql query를 그대로 사용
= 특정 디비에 의존성을 가진 쿼리
= 디비가 변경 되었을때 직접 코드 수정 없이 자동으로 변경해주는 jpa의 장점을 살릴 수 없다.
= 그렇기에 최소한의 사용을 권장

@Query(nativeQuery=true)해주면 됌
이 경우에는 jpql과 다르게 entity 쿼리들을 사용할 수 없다.
쿼리메소드에서는 @where 어노테이션이 동작하지만, native query에서는 포함되지 않는다.

  • native query
    native query를 사용할 때는 @transactional을 사용해야한다.
    네이티브 쿼리를 사용하면 @where를 사용했던 쿼리들을 무시하고 동작한다.
    jpa에서 지원하지 않는 기능들을 사용할 때
    @Modifying : update 사용할 때

0개의 댓글