4. 스프링 데이터 리포지토리 작업
Spring Data 저장소 추상화의 목표는 다양한 지속성 저장소에 대한 데이터 액세스 계층을 구현하는 데 필요한 상용구 코드의 양을 크게 줄이는 것입니다.
스프링 데이터 저장소 문서 및 모듈 이 장에서는 스프링 데이터 리포지토리의 핵심 개념과 인터페이스에 대해 설명합니다. 이 장의 정보는 Spring Data Commons 모듈에서 가져온 것입니다. JPA (Java Persistence API) 모듈에 대한 구성 및 코드 샘플을 사용합니다. XML 네임 스페이스 선언과 형식을 사용하는 특정 모듈과 동일하게 확장해야합니다. “ 네임 스페이스 레퍼런스 ”는 XML 설정을 다루며, 이는 저장소 API를 지원하는 모든 스프링 데이터 모듈에서 지원됩니다. “ 리포지토리 쿼리 키워드 ”는 일반적으로 리포지토리 추상화에서 지원되는 쿼리 방법 키워드를 다룹니다. 모듈의 특정 기능에 대한 자세한 내용은이 문서의 해당 모듈에 대한 장을 참조하십시오. |
4.1. 핵심 개념
Spring Data 저장소 추상화의 중앙 인터페이스는 Repository
입니다. 도메인 클래스의 ID 유형뿐만 아니라 도메인 클래스도 유형 인수로 관리해야합니다. 이 인터페이스는 주로 작업 할 유형을 캡처하고이를 확장하는 인터페이스를 발견하는 데 도움을주는 마커 인터페이스 역할을합니다. 는 CrudRepository
관리되는 엔티티 클래스에 대한 정교한 CRUD 기능을 제공합니다.
CrudRepository
인터페이스public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity); (1)
Optional<T> findById(ID primaryKey); (2)
Iterable<T> findAll(); (3)
long count(); (4)
void delete(T entity); (5)
boolean existsById(ID primaryKey); (6)
// … more functionality omitted.
}
1 | 주어진 엔티티를 저장합니다. |
2 | 주어진 ID로 식별 된 엔티티를 리턴합니다. |
3 | 모든 엔티티를 반환합니다. |
4 | 엔터티 수를 반환합니다. |
5 | 주어진 엔티티를 삭제합니다. |
6 | 주어진 ID를 가진 엔티티가 존재하는지 여부를 나타냅니다. |
우리는 또한 다음과 같은 특정 기술 추상화, 지속성 제공 JpaRepository 나 MongoRepository . 이러한 인터페이스 CrudRepository 는 기본 지속성 기술의 기능을 확장 하고 공개하는 대신 일반적인 지속성 기술과 무관 한 인터페이스를 제공 CrudRepository 합니다. |
또한 엔티티에 페이지 매김 된 액세스를 용이하게하는 추가 메소드를 추가 CrudRepository
하는 PagingAndSortingRepository
추상화가 있습니다.
PagingAndSortingRepository
인터페이스public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
User
페이지 크기가 20 인 두 번째 페이지에 액세스하려면 다음과 같은 작업을 수행 할 수 있습니다.
PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));
쿼리 방법 외에도 개수 및 삭제 쿼리에 대한 쿼리 파생을 사용할 수 있습니다. 다음 목록은 파생 카운트 쿼리에 대한 인터페이스 정의를 보여줍니다.
interface UserRepository extends CrudRepository<User, Long> {
long countByLastname(String lastname);
}
다음 목록은 파생 삭제 쿼리에 대한 인터페이스 정의를 보여줍니다.
interface UserRepository extends CrudRepository<User, Long> {
long deleteByLastname(String lastname);
List<User> removeByLastname(String lastname);
}
4.2. 쿼리 방법
표준 CRUD 기능 리포지토리에는 일반적으로 기본 데이터 스토어에 대한 쿼리가 있습니다. Spring Data를 사용하면 이러한 쿼리를 선언하는 것이 4 단계 프로세스가됩니다.
- 다음 예제와 같이 리포지토리 또는 해당 하위 인터페이스 중 하나를 확장하는 인터페이스를 선언하고 처리해야하는 도메인 클래스 및 ID 유형으로 입력하십시오.
interface PersonRepository extends Repository<Person, Long> { … }
- 인터페이스에서 쿼리 메소드를 선언하십시오.
interface PersonRepository extends Repository<Person, Long> { List<Person> findByLastname(String lastname); }
- JavaConfig 또는 XML 구성을 사용하여 해당 인터페이스에 대한 프록시 인스턴스를 작성하도록 Spring을 설정하십시오 .
- Java 구성을 사용하려면 다음과 유사한 클래스를 작성하십시오.
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories class Config { … }
- XML 구성을 사용하려면 다음과 유사한 Bean을 정의하십시오.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="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"> <jpa:repositories base-package="com.acme.repositories"/> </beans>
이 예제에서는 JPA 네임 스페이스가 사용됩니다. 다른 상점에 저장소 저장소를 사용하는 경우이를 상점 모듈의 적절한 네임 스페이스 선언으로 변경해야합니다. 즉,
jpa
예를 들어을 선호하여 교환해야합니다mongodb
.+ 또한 주석이 달린 클래스의 패키지가 기본적으로 사용되므로 JavaConfig 변형은 패키지를 명시 적으로 구성하지 않습니다. 스캔 할 패키지를 사용자 정의하려면
basePackage…
데이터 저장소 특정 저장소의 속성 중 하나를 사용하십시오@Enable${store}Repositories
. - Java 구성을 사용하려면 다음과 유사한 클래스를 작성하십시오.
- 다음 예제와 같이 저장소 인스턴스를 삽입하여 사용하십시오.
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
다음 섹션에서는 각 단계를 자세히 설명합니다.
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/#repositories
'IT > Spring-Data-JPA' 카테고리의 다른 글
스프링 데이터 JPA #Reference:지속 엔티티 (0) | 2020.06.19 |
---|---|
스프링 데이터 JPA #Intro:레포지터리 작업 (4) (0) | 2020.06.19 |
스프링 데이터 JPA #Intro:레포지터리 작업 (3) (0) | 2020.06.19 |
스프링 데이터 JPA #Intro:레포지터리 작업 (2) (0) | 2020.06.19 |
스프링 데이터 JPA #Intro (0) | 2020.06.19 |