스프링 데이터 JPA #Intro:레포지터리 작업 (3)
4.5. 리포지토리 인스턴스 생성
이 섹션에서는 정의 된 저장소 인터페이스에 대한 인스턴스 및 Bean 정의를 작성합니다. 이를 수행하는 한 가지 방법은 저장소 메커니즘을 지원하는 각 Spring Data 모듈과 함께 제공되는 Spring 네임 스페이스를 사용하는 것입니다. 일반적으로 Java 구성을 사용하는 것이 좋습니다.
4.5.1. XML 구성
각 스프링 데이터 모듈에는 repositories
다음 예제와 같이 스프링이 스캔하는 기본 패키지를 정의 할 수 있는 요소가 포함되어 있습니다.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<repositories base-package="com.acme.repositories" />
</beans:beans>
앞의 예제에서 Spring은 com.acme.repositories
인터페이스 Repository
와 그 하위 인터페이스 중 하나를 확장하기 위해 모든 하위 패키지 를 스캔하도록 지시 받습니다. 발견 된 각 인터페이스에 대해 인프라는 지속성 기술 고유 FactoryBean
를 등록 하여 쿼리 메소드의 호출을 처리하는 적절한 프록시를 작성합니다. 각 Bean은 인터페이스 이름에서 파생 된 Bean 이름 UserRepository
으로 등록 되므로의 인터페이스 는에서 등록됩니다 userRepository
. 이 base-package
속성은 와일드 카드를 허용하므로 스캔 한 패키지의 패턴을 정의 할 수 있습니다.
필터 사용
기본적으로 인프라는 Repository
구성된 기본 패키지 아래에있는 지속성 기술 특정 하위 인터페이스를 확장하는 모든 인터페이스를 선택하고 이에 대한 Bean 인스턴스를 작성합니다. 그러나 어떤 인터페이스에 대해 Bean 인스턴스가 작성되었는지에 대한보다 세밀한 제어가 필요할 수 있습니다. 그렇게하려면 요소 내부의 <include-filter />
및 <exclude-filter />
요소를 사용 하십시오 <repositories />
. 시맨틱은 Spring의 컨텍스트 네임 스페이스에있는 요소와 정확히 동일합니다. 자세한 내용 은 이러한 요소에 대한 Spring 참조 설명서 를 참조 하십시오 .
예를 들어, 인스턴스 인터페이스에서 특정 인터페이스를 저장소 Bean으로 제외하려면 다음 구성을 사용할 수 있습니다.
<repositories base-package="com.acme.repositories">
<context:exclude-filter type="regex" expression=".*SomeRepository" />
</repositories>
앞의 예 SomeRepository
는 인스턴스화로 끝나는 모든 인터페이스를 제외합니다 .
4.5.2. JavaConfig
@Enable${store}Repositories
JavaConfig 클래스에서 상점 특정 어노테이션을 사용하여 저장소 인프라를 트리거 할 수도 있습니다 . Spring 컨테이너의 Java 기반 구성에 대한 소개 는 Spring 참조 문서의 JavaConfig를 참조하십시오 .
스프링 데이터 리포지토리를 활성화하기위한 샘플 구성은 다음과 같습니다.
@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {
@Bean
EntityManagerFactory entityManagerFactory() {
// …
}
}
위의 예제는 JPA 특정 어노테이션을 사용하며 실제로 사용하는 상점 모듈에 따라 변경됩니다. EntityManagerFactory Bean 의 정의에도 동일하게 적용됩니다 . 상점 특정 구성을 다루는 섹션을 참조하십시오. |
4.5.3. 독립형 사용법
CDI 환경과 같이 스프링 컨테이너 외부에서 저장소 인프라를 사용할 수도 있습니다. 여전히 클래스 경로에 일부 Spring 라이브러리가 필요하지만 일반적으로 프로그래밍 방식으로 리포지토리를 설정할 수도 있습니다. 저장소 지원을 제공하는 Spring Data 모듈 RepositoryFactory
은 다음과 같이 사용할 수 있는 지속성 기술을 제공합니다 .
RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);
4.6. 스프링 데이터 리포지토리를위한 커스텀 구현
이 섹션에서는 저장소 사용자 정의 및 단편이 복합 저장소를 형성하는 방법에 대해 설명합니다.
쿼리 방법에 다른 동작이 필요하거나 쿼리 파생으로 구현할 수없는 경우 사용자 지정 구현을 제공해야합니다. Spring Data 리포지토리를 사용하면 사용자 지정 리포지토리 코드를 제공하고 일반 CRUD 추상화 및 쿼리 방법 기능과 통합 할 수 있습니다.
4.6.1. 개별 리포지토리 사용자 지정
사용자 정의 기능으로 저장소를 보강하려면 먼저 다음 예제와 같이 조각 인터페이스 및 사용자 정의 기능에 대한 구현을 정의해야합니다.
interface CustomizedUserRepository {
void someCustomMethod(User user);
}
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
public void someCustomMethod(User user) {
// Your custom implementation
}
}
프래그먼트 인터페이스에 해당하는 클래스 이름의 가장 중요한 부분은 Impl 접미사입니다. |
구현 자체는 스프링 데이터에 의존하지 않으며 일반적인 스프링 빈이 될 수 있습니다. 결과적으로 표준 종속성 주입 동작을 사용하여 다른 Bean (예 :)에 대한 참조를 주입 JdbcTemplate
하고 측면에 참여 하는 등의 작업을 수행 할 수 있습니다.
그러면 다음 예제와 같이 리포지토리 인터페이스가 조각 인터페이스를 확장 할 수 있습니다.
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {
// Declare query methods here
}
저장소 인터페이스로 프래그먼트 인터페이스를 확장하면 CRUD와 사용자 정의 기능이 결합되어 클라이언트에서 사용할 수 있습니다.
스프링 데이터 리포지토리는 리포지토리 구성을 형성하는 조각을 사용하여 구현됩니다. 프래그먼트는 기본 리포지토리, 기능적 측면 (예 : QueryDsl ) 및 사용자 정의 인터페이스 및 해당 구현입니다. 저장소 인터페이스에 인터페이스를 추가 할 때마다 조각을 추가하여 컴포지션을 향상시킵니다. 기본 저장소 및 저장소 측면 구현은 각 Spring Data 모듈에서 제공합니다.
다음 예제는 사용자 정의 인터페이스 및 해당 구현을 보여줍니다.
interface HumanRepository {
void someHumanMethod(User user);
}
class HumanRepositoryImpl implements HumanRepository {
public void someHumanMethod(User user) {
// Your custom implementation
}
}
interface ContactRepository {
void someContactMethod(User user);
User anotherContactMethod(User user);
}
class ContactRepositoryImpl implements ContactRepository {
public void someContactMethod(User user) {
// Your custom implementation
}
public User anotherContactMethod(User user) {
// Your custom implementation
}
}
다음 예제는 확장되는 사용자 정의 저장소의 인터페이스를 보여줍니다 CrudRepository
.
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {
// Declare query methods here
}
리포지토리는 선언 순서대로 가져온 여러 개의 사용자 지정 구현으로 구성 될 수 있습니다. 사용자 정의 구현은 기본 구현 및 저장소 측면보다 우선 순위가 높습니다. 이 순서를 사용하면 기본 저장소 및 측면 메소드를 대체하고 두 조각이 동일한 메소드 서명에 기여하는 경우 모호성을 해결합니다. 리포지토리 조각은 단일 리포지토리 인터페이스에서 사용하도록 제한되지 않습니다. 여러 리포지토리가 조각 인터페이스를 사용하여 서로 다른 리포지토리에서 사용자 지정을 다시 사용할 수 있습니다.
다음 예제는 저장소 조각 및 해당 구현을 보여줍니다.
save(…)
interface CustomizedSave<T> {
<S extends T> S save(S entity);
}
class CustomizedSaveImpl<T> implements CustomizedSave<T> {
public <S extends T> S save(S entity) {
// Your custom implementation
}
}
다음 예제는 선행 저장소 단편을 사용하는 저장소를 보여줍니다.
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}
interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}
구성
네임 스페이스 구성을 사용하는 경우 리포지토리 인프라는 리포지토리를 찾은 패키지 아래의 클래스를 검색하여 사용자 지정 구현 조각을 자동 검색합니다. 이러한 클래스는 네임 스페이스 요소의 repository-impl-postfix
속성을 조각 인터페이스 이름 에 추가하는 명명 규칙을 따라야합니다 . 이 접미사는 기본적으로 Impl
입니다. 다음 예는 기본 접미사를 사용하는 저장소와 접미사에 대한 사용자 정의 값을 설정하는 저장소를 보여줍니다.
<repositories base-package="com.acme.repository" />
<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />
이전 예제의 첫 번째 구성은 com.acme.repository.CustomizedUserRepositoryImpl
사용자 정의 저장소 구현으로 작동하기 위해 호출 된 클래스를 찾으려고 시도합니다 . 두 번째 예는 조회를 시도합니다 com.acme.repository.CustomizedUserRepositoryMyPostfix
.
모호성의 해결
클래스 이름이 일치하는 여러 구현이 다른 패키지에있는 경우 Spring Data는 Bean 이름을 사용하여 사용할 이름을 식별합니다.
CustomizedUserRepository
앞에서 설명한 두 가지 사용자 지정 구현을 고려할 때 첫 번째 구현이 사용됩니다. Bean 이름은 customizedUserRepositoryImpl
조각 인터페이스 ( CustomizedUserRepository
)와 접미사 이름 과 일치합니다 Impl
.
package com.acme.impl.one;
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
package com.acme.impl.two;
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
// Your custom implementation
}
로 UserRepository
인터페이스에 주석을 달면 @Component("specialCustom")
Bean 이름 플러스 Impl
는의 저장소 구현에 정의 된 것과 일치 com.acme.impl.two
하며 첫 번째 대신 사용됩니다.
수동 배선
커스텀 구현이 주석 기반 구성과 자동 배선만을 사용하는 경우, 앞의 접근법은 다른 스프링 빈으로 취급되기 때문에 잘 작동합니다. 구현 프래그먼트 Bean에 특수 배선이 필요한 경우, 이전 섹션 에서 설명한 규칙에 따라 Bean을 선언하고 이름을 지정할 수 있습니다 . 그런 다음 인프라는 직접 정의하지 않고 이름으로 수동으로 정의 된 Bean 정의를 참조합니다. 다음 예제는 사용자 정의 구현을 수동으로 연결하는 방법을 보여줍니다.
<repositories base-package="com.acme.repository" />
<beans:bean id="userRepositoryImpl" class="…">
<!-- further configuration -->
</beans:bean>
4.6.2. 기본 리포지토리 사용자 지정
이전 섹션 에서 설명한 접근 방식은 모든 저장소가 영향을 받도록 기본 저장소 동작을 사용자 정의하려는 경우 각 저장소 인터페이스를 사용자 정의해야합니다. 대신 모든 리포지토리의 동작을 변경하기 위해 지속성 기술 별 리포지토리 기본 클래스를 확장하는 구현을 만들 수 있습니다. 그런 다음이 클래스는 다음 예제와 같이 저장소 프록시의 사용자 정의 기본 클래스 역할을합니다.
class MyRepositoryImpl<T, ID>
extends SimpleJpaRepository<T, ID> {
private final EntityManager entityManager;
MyRepositoryImpl(JpaEntityInformation entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);
// Keep the EntityManager around to used from the newly introduced methods.
this.entityManager = entityManager;
}
@Transactional
public <S extends T> S save(S entity) {
// implementation goes here
}
}
이 클래스에는 상점 특정 저장소 팩토리 구현이 사용하는 수퍼 클래스의 생성자가 있어야합니다. 저장소 기본 클래스에 여러 생성자가있는 EntityInformation 경우 상점 특정 인프라 스트럭처 오브젝트 (예 : EntityManager 또는 템플리트 클래스)를 사용 하는 생성자를 대체하십시오 . |
마지막 단계는 Spring Data 인프라가 사용자 정의 된 저장소 기본 클래스를 인식하도록하는 것입니다. Java 구성에서는 다음 예제와 같이 주석 의 repositoryBaseClass
속성을 사용하여이를 수행 할 수 있습니다 @Enable${store}Repositories
.
@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
다음 예제와 같이 XML 네임 스페이스에서 해당 속성을 사용할 수 있습니다.
<repositories base-package="com.acme.repository"
base-class="….MyRepositoryImpl" />
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. |
출처 : docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.create-instances