Back End/Spring Data JPA

[Spring JPA] 쿼리메소드, JPQL, NativeQuery (@Query)

DevPing9_ 2021. 11. 1. 22:33

# JPA 자체 제공 쿼리메소드

 

Spring Data JPA - Reference Documentation

Example 109. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del

docs.spring.io


# JPQL

  • @Query 로 구현 가능한 JPA SQL
  • ORM을 위해 구현된 JPA므로, JPQL로 작성한 쿼리문들은 알아서 DB에 맞게 dialect 처리되어 각 DB에 맞는 query문을 생성한다.
  • 예시_) @Query("select distinct u from User u join fetch u.shoppinglists") 와 같이 객체타입으로 사용할 수 있다.
  • https://docs.oracle.com/html/E13946_04/ejb3_langref.html#ejb3_langref_select  
 

10.2. JPQL Language Reference

The SELECT clause denotes the query result. More than one value may be returned from the SELECT clause of a query. The SELECT clause may contain one or more of the following elements: a single range variable or identification variable that ranges over an e

docs.oracle.com


# NativeQuery

  • @Query 로 구현 가능한 native query
  • 각 DB에 맞게 정확한 natvie query 를 작성해야한다.
  • 예시_) @Query(value="select * from user order by id desc", nativeQuery = true) 와 같이 JPQL과 다르게 user는 소문자로 표기되어 있다. (DB에 생성된 테이블을 그대로 써야한다. 그냥 진짜 깡 SQL문이다)
  • Listener 와 @Where 같은 JPA 기능을 사용하지 않고, 작성된 쿼리문만 실행한다. (중요)

# 그럼 각각 존재이유는 무엇일까?

  • 보통 NativeQuery는 JPA의 성능이슈를 회피하기 위해 사용된다.
  • (업데이트를 한방에 날리고 싶을 떄 등 불필요한 쿼리를 생성하지 않기 위해 사용된다.)
  • JPQL 은 JPA 자체 제공 Keyword 쿼리 메소드로 이름의 가독성이 떨어질 경우와 성능을 개선하고 싶을 때 사용된다.
  • JPQL과 Keyword 쿼리메소드는 Listner와 @Where 같은 JPA 기능을 그대로 사용한다.
728x90