Spring Data JPA
개요
Spring Data JPA는 Jakarta Persistence API(JPA)에 대한 Repository 지원을 제공합니다.
JPA 데이터 소스에 액세스해야 하는 일관된 프로그래밍 모델로 애플리케이션 개발을 용이하게 합니다
간단한 사용법
Examples Repository ( 예제 Repository )
The GitHub spring-data-examples repository hosts several examples that you can download and play around with to get a feel for how the library works.
아래는 간단한 사용법 예제 코드입니다.
- Entity ( Person )
@Entity
class Person {
@Id // key 값을 의미
@GeneratedValue(strategy = GenerationType.AUTO) // autoincrement 사용하겠다는 것을 의미
private Long id;
private String name;
// getters and setters omitted for brevity
}
- Repository ( PersonRepository )
interface PersonRepository extends Repository<Person, Long> {
Person save(Person person); // Person 객체를 저장하는 함수
Optional<Person> findById(long id); // id로 Person 객체를 찾아서 반환
}
- SpringBootApplication에서 사용법
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner runner(PersonRepository repository) {
return args -> {
Person person = new Person(); // Person 객체 생성
person.setName("John"); // Person 객체의 Name변수에 "John" 넣기
repository.save(person); // 저장
Person saved = repository.findById(person.getId()).orElseThrow(NoSuchElementException::new);
};
}
}
핵심 개념
Spring Data 저장소 추상화의 중심 인터페이스는 Repository 이며, 도메인 클래스를 관리하고, 도메인 클래스의 식별자 유형을 유형 인수로 사용하며, 이 인터페이스는 주로 작업할 유형을 확인하고, 이 interface를 확장하는 interface를 발견하는 데 도움이 되는 marker interface 역할을 한다.
*CrudRepository Interface*
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity); // entity 저장하는 함수
Optional<T> findById(ID primaryKey); // id값을 매개변수로 일지하는 entity를 반환하는 함수
Iterable<T> findAll(); // entity 전부를 반환하는 함수
long count(); // entity 수를 반환하는 함수
void delete(T entity); // 매개변수로 주어진 entity를 삭제하는 함수
boolean existsById(ID primaryKey); // id값을 매개변수로 entity가 존재 여부를 반환하는 함수
// … more functionality omitted.
}
이 인터페이스에 선언된 메서드를 일반적으로 CRUD 메서드라고 합니다. ListCrudRepository는 이와 동등한 메서드를 제공하지만 CrudRepository 메서드가 Itable을 반환하는 경우 List를 반환합니다.
또한 JpaRepository 또는 MongoRepository와 같은 지속성 기술별 추상화를 제공합니다. 이러한 인터페이스는 CrudRepository를 확장하고 CrudRepository와 같은 다소 일반적인 지속성 기술에 구애 받지 않는 인터페이스 외에도 기본 지속성 기술의 기능을 노출합니다.
예를 들어 페이지 크기가 20인 두 번째 페이지에 액세스하려면 User다음과 같이 할 수 있습니다.
PagingAndSortingRepository<User, Long> repository = // 페이지로 가져올 Bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));
ListPagingAndSortingRepository는 동일한 방법을 제공하지만 PagingAndSortingRepository 메서드가 Itable을 반환하는 경우에는 List를 반환합니다.