[Spring] Spring Data Jpa 메소드 이름으로 쿼리 생성하기
스프링 데이터 jpa는 메소드 이름을 선언해주면 이름을 분석해 jpql 쿼리를 실행시켜준다.
순수 jpa 레포지토리로 구현한 함수가 이런 형태라면
public List<Member> findByUsernameAndAgeGreaterThan(String username, int age) {
return em.createQuery("select m from Member m where m.username = :username
and m.age > :age")
.setParameter("username", username)
.setParameter("age", age)
.getResultList();
}
스프링 데이터 jpa는
public interface MemberRepository extends JpaRepository<Member, Long> {
List<Member> findByUsernameAndAgeGreaterThan(String username, int age);
}
이렇게 jpa레포지토리를 상속받고 선언만 해주면 같은 결과값을 받을 수 있다.
쿼리 메소드 필터 조건은 해당문서를 참고하면 된다.
Spring Data JPA - Reference Documentation
스프링 데이터 jpa가 제공하는 쿼리 메소드 기능은 여러가지가 있는데,
- 조회 : find...By, read...By, query...By, get...By
참고(Spring Data JPA - Reference Documentation)
- count : count...By 반환타입 long
- exists : exists...By 반환타입 boolean
- 삭제 : delete...By, remove...By 반환타입 long
- distinct : findDistinct, findMemberDistinctBy
- Limit : findFirst3, findFirst, findTop, findTop3
참고(Spring Data JPA - Reference Documentation)
조건부도 종류가 많다.
able 3. Supported keywords inside method names
Keyword | Sample | JPQL snippet |
Distinct | findDistinctByLastnameAndFirstname | select distinct … where x.lastname = ?1 and x.firstname = ?2 |
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is, Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull, Null | findByAge(Is)Null | … where x.age is null |
IsNotNull, NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection<Age> ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> ages) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstname) = UPPER(?1) |
스프링 데이터 jpa는 또 하나의 장점이 있는데,
엔티티의 필드명이 변경되면 인터페이스에 정의한 메소드 이름도 함께 변경해줘야만 하는 것이다.
그렇지 않으면 어플리케이션을 시작하는 시점에 오류가 발생하다.
이렇게 어플리케이션 로딩 시점에 오류를 인지할 수 있는 것은 스프링 데이터 jpa의 매우 큰 장점이다.