리포지토리의 쿼리 메서드는 Spring Data JPA에서 제공하는 기능으로, 데이터베이스 쿼리를 메서드 이름으로 자동 생성해주는 기능이다. 이를 사용하면 SQL 쿼리를 직접 작성하지 않고도 데이터를 조회, 삽입, 수정, 삭제 등을 수행할 수 있다.
예를 들어, 다음과 같은 엔티티 클래스가 있다고 가정해보자
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
private int quantity;
}
이 엔티티를 다루는 리포지토리를 만들어보자
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProductRepository extends JpaRepository<Product, Long> {
// 이름으로 제품 조회
List<Product> findByName(String name);
// 가격이 특정 범위 내에 있는 제품 조회
List<Product> findByPriceBetween(double minPrice, double maxPrice);
// 수량이 특정 값 이상인 제품 조회
List<Product> findByQuantityGreaterThanEqual(int quantity);
}
@Query 어노테이션은 Spring Data JPA에서 제공하는 기능으로, 사용자가 직접 JPQL(QueryDSL) 또는 Native SQL 쿼리를 작성하여 레포지토리 메서드에 매핑할 수 있도록 해준다. 이를 통해 기본적인 쿼리 메서드로 처리하기 어려운 복잡한 쿼리를 수행할 수 있다.@Query 어노테이션은 메서드에 적용되며, 해당 메서드가 실행될 때 지정된 쿼리를 실행하게 된다. @Query 어노테이션을 사용하면 메서드 이름 규칙을 따르지 않고도 원하는 쿼리를 작성할 수 있다.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface ProductRepository extends JpaRepository<Product, Long> {
// 이름으로 제품 조회
@Query("SELECT p FROM Product p WHERE p.name = :name")
List<Product> findByName(@Param("name") String name);
// 가격이 특정 범위 내에 있는 제품 조회
@Query("SELECT p FROM Product p WHERE p.price BETWEEN :minPrice AND :maxPrice")
List<Product> findByPriceBetween(@Param("minPrice") double minPrice, @Param("maxPrice") double maxPrice);
// 수량이 특정 값 이상인 제품 조회
@Query("SELECT p FROM Product p WHERE p.quantity >= :quantity")
List<Product> findByQuantityGreaterThanEqual(@Param("quantity") int quantity);
}