본문 바로가기
🍃SpringFrameworks/SpringDataJPA

[JPA] Query Method. 쿼리 메서드

by inbeom 2023. 9. 10.
728x90

Spring Data JPA에서 제공하는 공동 인터페이스는 기본적인 CRUD를 제공해준다. (JpaRepository)

 

JpaRepository<T, ID>

  1. Entity의 클래스명 + Repository 로 인터페이스 생성
  2. JpaRepository 상속 (extends)
  3. <>속성으로 ‘Entity의 클래스명’, ‘Entity기본키(Id)의 타입’ 지정

 

💡 QueryMethod 이름 지정

  • 간단한 쿼리일 경우 이와 같은 쿼리 메서드를 이용한다.
  • 같은 분류의 메서드는 이름만 다를 뿐 똑같은 기능을 한다.
  • (조회 : find..By, read..By, get…By 등)

spring data JPA - 참조 문서 (spring.io)

 

QueryMethod 필터 조건

쿼리 조건 메서드명   실제 쿼리문
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 findByFirstnamefindByFirstnameIsfindByFirstnameEquals … 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)

 

메서드 정의
List<User> findByIdAfter(LocalDateTime localDateTime);

 

메서드 활 용

System.*out*.println("findByIdAfter : " + userRepository.findByIdAfter(4));

 

@Query

  • @Query 어노테이션을 사용해 Custom으로 쿼리문을 지정할 수 있다.

728x90

'🍃SpringFrameworks > SpringDataJPA' 카테고리의 다른 글

[JPA] 1:1 Relation. 관계 설정  (0) 2023.09.10
[JPA] Entity Listener. 엔티티 리스너  (0) 2023.09.10
[JPA] JPA Annotation. 어노테이션  (0) 2023.09.10
[JPA] H2 Database  (0) 2023.09.10
[JPA] JPA란?  (0) 2023.09.10