1. Spring Data JPA란?

  • JPA 를 편리하게 사용하기 위해, 스프링에서 JPA 를 Wrapping
  • 스프링 개발자들이 JPA 를 사용할 때 필수적으로 생성해야 하나, 예상 가능하고 반복적인 코드들 → Spring Data JPA 가 대신 작성
  • Repostiory 인터페이스만 작성하면, 필요한 구현은 스프링이 대신 알아서 척척!

 

 

2. 기본 제공 기능

// 1. 상품 생성
Product product = new Product(...);
productRepository.save(product);

// 2. 상품 전체 조회
List<Product> products = productRepository.findAll();

// 3. 상품 전체 개수 조회
long count = productRepository.count();

// 4. 상품 삭제
productRepository.delete(product);

 

 

3. Repository 코드 예제

  1) 

public interface ProductRepository extends JpaRepository<Product, Long> {
	// (1) 회원 ID 로 등록된 상품들 조회
	List<Product> findAllByUserId(Long userId);

	// (2) 상품명이 title 인 관심상품 1개 조회
	Product findByTitle(String title);

	// (3) 상품명에 word 가 포함된 모든 상품들 조회 (LIKE 문)
	List<Product> findAllByTitleContaining(String word);

	// (4) 최저가가 fromPrice ~ toPrice 인 모든 상품들을 조회
	List<Product> findAllByLpriceBetween(int fromPrice, int toPrice);
}

 

  2)

// ModifiedAt으로 내림차순 정렬
List<Memo> findAllByOrderByModifiedAtDesc();

// ModifiedAt으로 내림차순 정렬 where ModifiedAt Between dateTime and dayBefore
List<Memo> findAllByModifiedAtBetweenOrderByModifiedAtDesc(LocalDateTime dateTime, LocalDateTime dayBefore);

where절 order절

 

 

 

** spring data JPA 공식 문서  : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods

+ Recent posts