You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public interface ItemRepository extends JpaRepository<Item, Long> {}
JpaRepository 인터페이스를 인터페이스 상속받고, 제네릭에 관리할 <엔티티, 엔티티ID>를 주면 됨.
➡️ 스프링 데이터 JPA가 구현 클래스를 대신 생성
JpaRepository 인터페이스만 상속 받으면 스프링 데이터 JPA가 프록시 기술을 사용해서 구현 클래스를 만들어준다.
만든 구현 클래스의 인스턴스를 만들어서 스프링 빈으로 등록한다.
개발자는 구현 클래스 없이 인터페이스만 만들면 기본 CRUD 기능을 사용할 수 있음
✅ 쿼리 메서드 기능
스프링 데이터 JPA는 인터페이스에 메서드만 적어두면, 메서드 이름을 분석해서 쿼리를 자동으로 만들고 실행해주는 기능을 제공
순수 JPA 리포지토리
순수 JPA를 사용하면 직접 JPQL을 작성하고, 파라미터도 직접 바인딩 해야 함
publicList<Member> findByUsernameAndAgeGreaterThan(Stringusername, intage) {
returnem.createQuery("select m from Member m where m.username = :username and m.age > :age")
.setParameter("username", username).setParameter("age", age)
.getResultList();
스프링 데이터 JPA는 메서드 이름을 분석해서 필요한 JPQL을 만들고 실행해준다. 물론 JPQL은 JPA가 SQL로 번역해서 실행한다.
물론 그냥 아무 이름이나 사용하는 것은 아니고 다음과 같은 규칙을 따라야 한다.
➡️ 스프링 데이터 JPA가 제공하는 쿼리 메소드 기능
조회: find...By ,read...By , query...By , get...By
예:) findHelloBy 처럼 ...에 식별하기 위한 내용(설명)이 들어가도 된다.
COUNT: count...By 반환타입 long
EXISTS: exists...By 반환타입 boolean
삭제: delete...By , remove...By 반환타입 long
DISTINCT: findDistinct , findMemberDistinctBy
LIMIT: findFirst3 , findFirst, findTop, findTop3
4️⃣ 스프링 데이터 JPA 적용 1
➡️ 설정
build.gradle 추가
spring-boot-starter-data-jpa 라이브러리 안에 JPA, 스프링 데이터 JPA, 스프링 JDBC 관련 기능 포함하고 있다.
따라서 안해줘도됨
//JPA, 스프링 데이터 JPA 추가implementation'org.springframework.boot:spring-boot-starter-data-jpa'
➡️ 적용
SpringDataJpaItemRepository
스프링 데이터 JPA가 제공하는 JpaRepository 인터페이스를 인터페이스 상속 받으면 기본적인 CRUD 기능을 사용할 수 있다.
이름으로 검색하거나, 가격으로 검색하는 기능은 공통으로 제공할 수 있는 기능이 아니다. 따라서 쿼리 메 서드 기능을 사용하거나 @query ****를 사용해서 직접 쿼리를 실행하면 된다.
publicinterfaceSpringDataJpaItemRepositoryextendsJpaRepository<Item, Long> {
List<Item> findByItemNameLike(StringitemName);
List<Item> findByPriceLessThanEqual(Integerprice);
//쿼리 메서드 (아래 메서드와 같은 기능 수행)List<Item> findByItemNameLikeAndPriceLessThanEqual(StringitemName, Integerprice);
//쿼리 직접 실행@Query("select i from Item i where i.itemName like :itemName and i.price <= :price")
List<Item> findItems(@Param("itemName") StringitemName, @Param("price")
Integerprice);
}
findAll()
코드에는 보이지 않지만 JpaRepository 공통 인터페이스가 제공하는 기능이다.
모든 Item 을 조회한다.
다음과 같은 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()
메서드 이름으로 쿼리를 실행하는 기능은 다음과 같은 단점이 있다.
조건이 많으면 메서드 이름이 너무 길어진다.
조인같은복잡한조건을사용할수없다.
메서드 이름으로 쿼리를 실행하는 기능은 간단한 경우에는 매우 유용하지만, 복잡해지면 직접 JPQL 쿼리를 작성하는 것이 좋다.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
데이터 접근 기술 - 스프링 데이터 JPA
1️⃣ 스프링 데이터 JPA 소개 1 - 등장 이유
2️⃣ 스프링 데이터 JPA 소개2 - 기능
Spring + JPA
3️⃣ 스프링 데이터 JPA 주요 기능
✅ 공통 인터페이스 기능
➡️ JpaRepository 사용법
➡️ 스프링 데이터 JPA가 구현 클래스를 대신 생성
✅ 쿼리 메서드 기능
스프링 데이터 JPA는 인터페이스에 메서드만 적어두면, 메서드 이름을 분석해서 쿼리를 자동으로 만들고 실행해주는 기능을 제공
순수 JPA 리포지토리
➡️ 스프링 데이터 JPA가 제공하는 쿼리 메소드 기능
4️⃣ 스프링 데이터 JPA 적용 1
➡️ 설정
➡️ 적용
findAll()
findByItemNameLike()
findByPriceLessThanEqual()
findByItemNameLikeAndPriceLessThanEqual()
findItems()
메서드 이름으로 쿼리를 실행하는 기능은 간단한 경우에는 매우 유용하지만, 복잡해지면 직접 JPQL 쿼리를 작성하는 것이 좋다.
All reactions