5.4. 저장 프로 시저
JPA 2.1 사양에서는 JPA 기준 쿼리 API를 사용하여 저장 프로 시저 호출을 지원합니다. @Procedure
리포지토리 메서드에 저장 프로 시저 메타 데이터를 선언하기위한 주석을 도입했습니다 .
다음 예는 다음 저장 프로 시저를 사용합니다.
plus1inout
HSQL DB 의 프로 시저 정의 ./;
DROP procedure IF EXISTS plus1inout
/;
CREATE procedure plus1inout (IN arg int, OUT res int)
BEGIN ATOMIC
set res = arg + 1;
END
/;
NamedStoredProcedureQuery
엔터티 유형 의 주석을 사용하여 저장 프로 시저의 메타 데이터를 구성 할 수 있습니다 .
@Entity
@NamedStoredProcedureQuery(name = "User.plus1", procedureName = "plus1inout", parameters = {
@StoredProcedureParameter(mode = ParameterMode.IN, name = "arg", type = Integer.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "res", type = Integer.class) })
public class User {}
참고 @NamedStoredProcedureQuery
저장 프로 시저에 대한 두 가지 다른 이름을 가지고있다. name
JPA가 사용하는 이름입니다. procedureName
저장 프로 시저가 데이터베이스에있는 이름입니다.
여러 가지 방법으로 저장소 메소드에서 스토어드 프로 시저를 참조 할 수 있습니다. 호출 할 저장 프로시 저는 주석 의 value
또는 procedureName
속성을 사용하여 직접 정의 할 수 있습니다 @Procedure
. 이것은 데이터베이스의 저장 프로 시저를 직접 참조하며를 통한 구성은 무시합니다 @NamedStoredProcedureQuery
.
또는 @NamedStoredProcedureQuery.name
속성을 속성으로 지정할 수 있습니다 @Procedure.name
. 경우도 value
, procedureName
도 name
구성된다 저장소 메소드의 이름으로서 사용되는 name
속성.
다음 예제는 명시 적으로 맵핑 된 프로 시저를 참조하는 방법을 보여줍니다.
@Procedure("plus1inout")
Integer explicitlyNamedPlus1inout(Integer arg);
다음 예제는 이전 예제와 동일하지만 procedureName
별명을 사용합니다 .
procedureName
별명을 통해 데이터베이스에서 이름이 "plus1inout"인 내재적으로 맵핑 된 프로 시저 참조@Procedure(procedureName = "plus1inout")
Integer callPlus1InOut(Integer arg);
다음은 앞의 두 속성과 동일하지만 명시 적 주석 속성 대신 메소드 이름을 사용합니다.
EntityManager
메소드 이름을 사용하여 내재적으로 맵핑 된 이름 지정된 스토어드 프로 시저 "User.plus1"참조@Procedure
Integer plus1inout(@Param("arg") Integer arg);
다음 예제는 @NamedStoredProcedureQuery.name
속성 을 참조하여 스토어드 프로 시저를 참조하는 방법을 보여줍니다 .
EntityManager
.@Procedure(name = "User.plus1IO")
Integer entityAnnotatedCustomNamedProcedurePlus1IO(@Param("arg") Integer arg);
호출되는 저장 프로 시저에 단일 출력 매개 변수가있는 경우 해당 매개 변수는 메소드의 리턴 값으로 리턴 될 수 있습니다. @NamedStoredProcedureQuery
주석 에 여러 개의 출력 매개 변수가 지정되어 있으면 주석에 지정된 Map
매개 변수 이름 인 키를 사용하여 반환 될 수 있습니다 @NamedStoredProcedureQuery
.
5.5. 명세서
JPA 2에는 프로그래밍 방식으로 쿼리를 작성하는 데 사용할 수있는 기준 API가 도입되었습니다. 를 작성하여 criteria
도메인 클래스에 대한 쿼리의 where 절을 정의합니다. 다시 한 번 물러 나면 이러한 기준은 JPA 기준 API 제한 조건으로 설명 된 엔티티에 대한 술어로 간주 될 수 있습니다.
Spring Data JPA는 Eric Evans의 책“Domain Driven Design”에서 동일한 개념을 따르고 JPA 기준 API로 이러한 사양을 정의하는 API를 제공하는 사양 개념을 취합니다. 스펙을 지원하기 위해 JpaSpecificationExecutor
다음과 같이 인터페이스를 사용하여 저장소 인터페이스를 확장 할 수 있습니다 .
public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
…
}
추가 인터페이스에는 다양한 방법으로 사양을 실행할 수있는 방법이 있습니다. 예를 들어, findAll
메소드는 다음 예제와 같이 스펙과 일치하는 모든 엔티티를 리턴합니다.
List<T> findAll(Specification<T> spec);
Specification
다음과 같은 인터페이스를 정의한다 :
public interface Specification<T> {
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
CriteriaBuilder builder);
}
스펙은 엔티티 위에 확장 가능한 술어 세트를 빌드하는 데 쉽게 사용할 수 있으며 JpaRepository
다음 예제와 같이 필요한 모든 조합에 대해 쿼리 (메소드)를 선언하지 않고도 결합하여 사용할 수 있습니다 .
public class CustomerSpecs {
public static Specification<Customer> isLongTermCustomer() {
return new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query,
CriteriaBuilder builder) {
LocalDate date = new LocalDate().minusYears(2);
return builder.lessThan(root.get(Customer_.createdAt), date);
}
};
}
public static Specification<Customer> hasSalesOfMoreThan(MonetaryAmount value) {
return new Specification<Customer>() {
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
CriteriaBuilder builder) {
// build query here
}
};
}
}
물론 상용구의 양은 개선의 여지가 있지만 (자바로 Java 8 클로저로 인해 감소 될 수 있음)이 섹션의 뒷부분에서 볼 수 있듯이 클라이언트 쪽이 훨씬 더 좋아집니다. Customer_
유형 JPA 메타 모델 생성 부 (투시하여 생성 된 메타 타입 에 대한 예는 절전 모드 구현의 문서 ). 따라서, 표현식 은 유형 이 속성 인 Customer_.createdAt
것으로 가정합니다 . 또한 비즈니스 요구 사항 추상화 수준에 대한 몇 가지 기준을 표현하고 executable을 만들었습니다 . 따라서 클라이언트는 다음과 같이 사용할 수 있습니다 .Customer
createdAt
Date
Specifications
Specification
List<Customer> customers = customerRepository.findAll(isLongTermCustomer());
이런 종류의 데이터 액세스에 대한 쿼리를 작성해보십시오. 단일을 사용하면 Specification
일반 쿼리 선언에 비해 많은 이점이 없습니다. 사양을 결합하여 새로운 Specification
객체 를 만들 때 사양의 힘이 실제로 빛납니다 . Specification
다음과 유사한 표현식을 작성하기 위해 제공 하는 기본 방법을 통해이를 달성 할 수 있습니다 .
MonetaryAmount amount = new MonetaryAmount(200.0, Currencies.DOLLAR);
List<Customer> customers = customerRepository.findAll(
isLongTermCustomer().or(hasSalesOfMoreThan(amount)));
Specification
Specification
인스턴스 를 체인화하고 결합하는 몇 가지“접착제 코드”기본 방법을 제공 합니다. 이러한 방법을 사용하면 새로운 Specification
구현 을 생성하고 기존 구현과 결합 하여 데이터 액세스 계층을 확장 할 수 있습니다 .
Spring Data JPA - Reference DocumentationOliver Gierke,Thomas Darimont,Christoph Strobl,Mark Paluch,Jay Bryant
version 2.3.1.RELEASE,2020-06-10 2.3.1.RELEASE © 2008-2019 The original authors. Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. |
출처 : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.stored-procedures
'IT > Spring-Data-JPA' 카테고리의 다른 글
스프링 데이터 JPA #부록 (0) | 2020.06.19 |
---|---|
스프링 데이터 JPA #Reference:트랜잭션 (0) | 2020.06.19 |
스프링 데이터 JPA #Reference:쿼리 (0) | 2020.06.19 |
스프링 데이터 JPA #Reference:지속 엔티티 (0) | 2020.06.19 |
스프링 데이터 JPA #Intro:레포지터리 작업 (4) (0) | 2020.06.19 |