728x90
JpaRepository 사용법
public interface ItemRepository extends JpaRepository<Member, Long> {
}
- JpaRepository 인터페이스를 인터페이스 상속 받고, 제네릭에 관리할 <엔티티, 엔티티ID> 를 주면 된다.
- JpaRepository 가 제공하는 기본 CRUD 기능을 모두 사용 가능
스프링 데이터 JPA가 제공하는 쿼리 메소드 기능
- 조회: find...By , read...By , query...By , get...By
ex) findHelloBy 처럼 ...에 식별하기 위한 내용(설명)이 들어가도 된다. - COUNT: count...By 반환타입 long
EXISTS: exists...By 반환타입 boolean
삭제: delete...By , remove...By 반환타입 long - DISTINCT: findDistinct , findMemberDistinctBy
- LIMIT: findFirst3 , findFirst , findTop , findTop3
JPQL 직접 사용하기
public interface SpringDataJpaItemRepository extends JpaRepository<Item, Long> {
//쿼리 메서드 기능
List<Item> findByItemNameLike(String itemName);
//쿼리 직접 실행
@Query("select i from Item i where i.itemName like :itemName and i.price <= :price")
List<Item> findItems(@Param("itemName") String itemName, @Param("price") Integer price);
}
→ @Query 와 함께 JPQL을 작성하면 된다.
적용
build.gradle 추가
//JPA, 스프링 데이터 JPA 추가
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
SpringDataJpaItemRepository
public interface SpringDataJpaItemRepository extends JpaRepository<Item, Long> {
List<Item> findByItemNameLike(String itemName);
List<Item> findByPriceLessThanEqual(Integer price);
//쿼리 메서드 (아래 메서드와 같은 기능 수행)
List<Item> findByItemNameLikeAndPriceLessThanEqual(String itemName, Integer price);
//쿼리 직접 실행
@Query("select i from Item i where i.itemName like :itemName and i.price <= :price")
List<Item> findItems(@Param("itemName") String itemName, @Param("price") Integer price);
}
findAll()
- 코드에는 보이지 않지만 JpaRepository 공통 인터페이스가 제공하는 기능
- JPQL : select i from Item i
findByItemNameLike()
- 이름 조건만 검색했을 때 사용하는 쿼리 메서드이다.
- JPQL : select i from Item i where i.name like ?
findByPriceLessThanEqual()
- 가격 조건만 검색했을 때 사용하는 쿼리 메서드이다.
- JPQL : select i from Item i where i.price <= ?
findByItemNameLikeAndPriceLessThanEqual()
- 이름과 가격 조건을 검색했을 때 사용하는 쿼리 메서드이다.
- JPQL : select i from Item i where i.itemName like ? and i.price <= ?
findItems() - 메서드 이름으로 쿼리 실행시 단점
1. 조건이 많으면 메서드 이름이 너무 길어진다.
2. 조인 같은 복잡한 조건을 사용할 수 없다.
→ 직접 JPQL 쿼리 작성하는게 좋다. (@Query)

스프링 데이터 JPA는 단순히 편리함을 넘어서 많은 개발자들이 똑같은 코드로 중복 개발하는 부분을 개선해준다.
반응형
'Spring > DB 2편' 카테고리의 다른 글
데이터 접근 기술 - 활용 방안 (0) | 2023.08.11 |
---|---|
데이터 접근 기술 - Querydsl (0) | 2023.08.11 |
데이터 접근 기술 - JPA (0) | 2023.08.10 |
데이터 접근 기술 - MyBatis (0) | 2023.08.10 |
데이터 접근 기술 -테스트 (0) | 2023.08.10 |