민우의 코딩일지
article thumbnail

 

 

 

 

 

 

 

 

쿼리 메소드(Query Method)

JPA에선 쿼리를 직접 작성하지않아도, 메소드 이름에 맞는 쿼리를 만들어주는 기능이 존재하는데, 

이번 포스팅에선 findBy ~~~ 로 사용할 수 있는 쿼리 메소드들에 대한 내용들로 정리해보았다. 🐣

 

 

📃 관련 문서

Spring Data JPA - Reference Documentation

 

Spring Data JPA - Reference Documentation

Example 11. Repository definitions using Domain Classes with mixed Annotations interface JpaPersonRepository extends Repository { … } interface MongoDBPersonRepository extends Repository { … } @Entity @Document public class Person { … } This example

docs.spring.io

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

findById를 포함한 다양한 쿼리 메소드들

참고로, findById에서 id는 identity(식별자)를 뜻하고. 식별하는 기준은 데이터베이스의 고유 식별번호 PK(Primary Key)인 대표키를 뜻한다.

 

 

기본 제공 메소드들

JPARepository 인터페이스의 상속 구조를 보면 다음과 같다.

 

CrudRepository, PagingAndSortingRepository, QueryByExampleExecutor 인터페이스를 상속받았음으로

기본적으로 상속받은 인터페이스의 각각의 메소드들을 모두 사용할 수 있다.

 

 

 

 

 

 

 

 

 

 

 

그 외 조합 가능한 메소드들

findBy + 컬럼명 + @

컬럼명뒤에 어떤 조건으로 쿼리를 실행하고싶은지 이름만 조합하면 그에 맞는 쿼리가 생성된다.

ex) findByTitleLike

 

 

조합가능한 단어들을 표로 정리해보았다.

출처는 Spring Data JPA 공식 사이트에 적혀있는 내용 그대로 복붙해서 한글로 살 -짝 수정

 

 

단어 레파지토리 메소드명 작성 예시 메소드 실행시 동작될 쿼리문 예시
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 널인것만 findByAgeIsNull … 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 오름차,내림차순(Asc/Desc) findByAgeOrderByLastnameAsc
, 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> age) … where x.age not in ?1
True true일때만 findByActiveTrue() … where x.active = true
False false일때만 findByActiveFalse() … where x.active = false
IgnoreCase 대소문자 관계없이 findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

쿼리 메소드 조합해서 사용해보기

 

 

어떤 쿼리 메소드를 사용할지 정해보자

예를 들어, 제목에 특정 단어와 일치하는것만 조회하고싶다면   Like 를 사용할 수 있다.

참고로, 일치가 아니라 포함으로 검색하고싶다면 Like 대신 Containing 을 사용하면된다.

 

 

 

 

 

 

 

정해진 쿼리 메소드를 조합해서 작성해보기

쿼리 메소드를 사용할땐,  findBy + 컬럼명 + 조건들 규칙에 맞춰서 작성하고, 레파지토리 파일에 카멜케이스로 작성한다.

카멜케이스: 개발자가 작명할때 사용하는 표기법중 하나,  첫글자는 소문자로 시작하고 이후 단어의 첫 글자를 대문자를 사용한다.

 

 

따라서  findByTitleLike 라고 작명하면된다.

다만, 이렇게만 작성하면 어떤 단어가 포함되어야할지 알 수가 없다.

 

그래서 단어를 받기 위해, 이름뒤에 매개변수를 사용해준다.

findByTitle(String keyword);

 

검색결과를 받기위해 리턴 타입을 적어줘야한다.

검색된 내용이 여러개(List)일 수 있으니 다음과 같이 작성해주었다.

List<DTO클래스파일명>  findByTitle(String keyword);

 

 

 

그래서, 다음과 같이 작성해주면 된다.

//public interface TestRepository extends JpaRepository<엔티티클래스명, Integer혹은Long> {
public interface TestRepository extends JpaRepository<TestEntity, Integer> {

    // List<엔티티클래스명> findBy + 컬럼명 + 조건(조건에 사용될 변수타입 & 이름)
    List<TestEntity> findByTitleLike(String keyword);
}
Repository외에도 Controller, Service, DTO, Entity 파일 작성이 필요하다.

 

 

 

 

 

 

 

쿼리 메소드 실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

깃허브

 

GitHub - ko0or/JPAstudy01: https://m1nwoo.tistory.com/tag/jpa

https://m1nwoo.tistory.com/tag/jpa. Contribute to ko0or/JPAstudy01 development by creating an account on GitHub.

github.com

 

src/main/resources/application.properties 파일의 2번째 라인에 기재된 local 이름은 수정 필요 ( 본인이 사용중인 스키마 이름으로 고쳐주기 )