Spring Data JPA 이해

송영재·2022년 11월 20일

Spring

목록 보기
32/45
  • 16) Spring Data JPA 는?

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

    • 상품 Enitity 선언
      @Entity
      public class Product extends Timestamped {
          @GeneratedValue(strategy = GenerationType.AUTO)
          @Id
          private Long id;
          private Long userId;
          private String title;
          private String image;
          private String link;
          private int lprice;
          private int myprice;
      }
    • Spring Data JPA) 상품 Repository 생성
      public interface ProductRepository extends JpaRepository<Product, Long> {
      }
    • Spring Data JPA) 기본 제공해 주는 기능
      // 1. 상품 생성
      Product product = new Product(...);
      productRepository.save(product);
      
      // 2. 상품 전체 조회
      List<Product> products = productRepository.findAll();
      
      // 3. 상품 전체 개수 조회
      long count = productRepository.count();
      
      // 4. 상품 삭제
      productRepository.delete(product);
    • ID 외의 필드에 대한 추가 기능은 interface 만 선언해 주면, 구현은 Spring Data JPA 가 대신!!
      public interface ProductRepository extends JpaRepository<Product, Long> {
          // (1) 회원 ID 로 등록된 상품들 조회
          List<Product> findAllByUserId(Long userId);
      
          // (2) 상품명이 title 인 관심상품 1개 조회
      		Product findByTitle(String title);
      
      		// (3) 상품명에 word 가 포함된 모든 상품들 조회
      		List<Product> findAllByTitleContaining(String word);
      
      		// (4) 최저가가 fromPrice ~ toPrice 인 모든 상품들을 조회
          List<Product> findAllByLpriceBetween(int fromPrice, int toPrice);
      }
    • Spring Data JPA 추가기능 구현방법은 공식문서(링크)에 명시되어 있음

0개의 댓글