본문 바로가기

Spring/JPA

Spring JPA - Spring data 저장소로 작업하기, 핵심 개념

 

 

1. The central interface in the Spring Data repository abstraction is Repository. It takes the domain class to manage as well as the ID type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The CrudRepository interface provides sophisticated CRUD functionality for the entity class that is being managed.

 

Spring Data 리포지토리 추상화의 중심 인터페이스는 Repository이다.

 

관리할 도메인 클래스와  도메인 클래스의 ID타입을 타입 인수로 한다. -> Repository<T, ID>

 

이 인터페이스는 주로 작업할 타입(유형)을 잡고, 이 인터페이스를 확장하는 인터페이스를 찾는것을 도움을 주는 마커 인터페이스 역할

-> 주로 작업할 것을 정해놓고, 이 인터페이스를 상속받은 인터페이스의  검색(?)을 돕는 인터페이스

cf) 마커 인터페이스: 자바의 마커 인터페이스는 일반적인 인터페이스와 동일하지만 사실상 아무 메소드도 선언하지 않은 인터페이스

 

CrudRepository 인터페이스는 관리되는 개체 클래스에 대한 정교한 CRUD기능을 제공한다.

 

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.
}

 

 

2. We also provide persistence technology-specific abstractions, such as JpaRepository or MongoRepository. Those interfaces extend CrudRepository and expose the capabilities of the underlying persistence technology in addition to the rather generic persistence technology-agnostic interfaces such as CrudRepository.

 

JpaRepository 또는 MongoRepository와 같은 영속성 기술 추상화를 제공한다.

이러한 인터페이스는 CrudRepository를 확장했고 CrudRepository와 같은 인터페이스의 다소 일반적인 영속성 기술에 더하여 기본적인 영속성 기술의 능력을 드러낸다.

-> CrudRepository를 상속받은 JpaRepository와 MongoRepository는 더 많은 영속화 기술을 제공한다.

 

 

3. On top of the CrudRepository, there is a PagingAndSortingRepository abstraction that adds additional methods to ease paginated access to entities:

 

개체에 접근하기 쉽게 페이지를 매기는 추가 메서드를 더한 PagingAndSortingRepository가 있다.

 

public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}


// 페이지 크기가 20인 두 번째 페이지에 접근
PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));

 

 

4. In addition to query methods, query derivation for both count and delete queries is available. 

 

쿼리 메서드외에 개수를 세고 삭제하는 쿼리 둘 다 파생해서 쓸 수 있다.

 

interface UserRepository extends CrudRepository<User, Long> {

  long countByLastname(String lastname); // lastname개수를 세는 파생 카운트 쿼리
}

interface UserRepository extends CrudRepository<User, Long> {

  long deleteByLastname(String lastname); // lastname 삭제하는 파생 쿼리

  List<User> removeByLastname(String lastname);
}

 

 

레퍼런스

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts

 

Spring Data JPA - Reference Documentation

Example 109. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del

docs.spring.io