[Spring Data JPA] QueryMethod

2023. 10. 14. 10:04·Web & Android/Spring Data JPA

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

  • 조인 불가
  • Repository 인터페이스에 간단한 네이밍 룰을 이용하여 메소드를 작성하면 원하는 쿼리 실행 가능
  • 엔티티의 이름은 생략 가능, By 뒤에는 검색할 때 사용할 변수의 이름 작성
  • 조건이 많을 때 쿼리 메소드를 선언하면 이름이 길어져 오히려 보기 힘들다는 단점이 있음 → 그래서 @Query 어노테이션 사용

JpaRepository<T, ID>

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

  long countByLastname(String lastname);
}

💡 QueryMethod 이름 지정

find + (엔티티 이름) + By + 변수 이름
@Test
@DisplayName("상품명, 상품상세설명 or 테스트")
public void findByItemNmOrItemDetailTest() {
		this.createItemList();
		List<Item> itemList = itemRepository.findByItemNmOrItemDetail("테스트 상품1", "테스트 상품 상세 설명5");
		for(Item item : itemList) {
				System.out.println(item.toString());
		}
	}
import com.shop.entity.Item;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemRepository extends JpaRepository<Item, Long> {

			List<Item> findByItemNm(String itemNm);

			List<Item> findByItemNmOrItemDetail(String itemNm, String itemDetail);

}

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);

 

저작자표시 비영리 변경금지 (새창열림)

'Web & Android > Spring Data JPA' 카테고리의 다른 글

[Spring Data JPA] Querydsl  (1) 2023.10.15
[Spring Data JPA] @Query  (0) 2023.10.14
[Spring Data JPA] JPA  (0) 2023.10.14
[Spring Data JPA] 영속성 컨텍스트  (1) 2023.10.14
[Spring Data JPA] ORM & SQL Mapper  (0) 2023.10.14
'Web & Android/Spring Data JPA' 카테고리의 다른 글
  • [Spring Data JPA] @Query
  • [Spring Data JPA] JPA
  • [Spring Data JPA] 영속성 컨텍스트
  • [Spring Data JPA] ORM & SQL Mapper
woojin._.
woojin._.
여러가지 개발을 해보며 발생하는 이야기들에 대한 블로그입니다:)
  • woojin._.
    Jin's Dev Story
    woojin._.
  • 전체
    오늘
    어제
    • 분류 전체보기 (829)
      • Tools (25)
        • eGovFrame (3)
        • GeoServer (3)
        • QGIS (2)
        • LabelImg (2)
        • Git (6)
        • GitHub (1)
        • Eclipse (7)
        • Visual Studio (1)
      • Web & Android (121)
        • SpringBoot (37)
        • Three.js (2)
        • Spring Data JPA (9)
        • 스프링 부트 쇼핑몰 프로젝트 with JPA (25)
        • Thymeleaf (4)
        • Spring Security (15)
        • Flutter (29)
      • Programming Language (61)
        • JAVA (27)
        • JavaScript (14)
        • Dart (2)
        • Python (15)
        • PHP (3)
      • Database (43)
        • PostgreSQL (32)
        • MYSQL (7)
        • Oracle (3)
        • MSSQL (1)
      • SERVER (17)
        • TCP_IP (3)
        • 리눅스 (7)
        • AWS (7)
      • Coding Test (445)
        • 백준[JAVA] (108)
        • 프로그래머스[JAVA] (260)
        • 알고리즘 고득점 Kit[JAVA] (3)
        • SQL 고득점 Kit[ORACLE] (74)
      • CS 지식 (49)
        • [자료구조] (14)
        • [네트워크] (12)
        • [데이터베이스] (10)
        • [알고리즘] (9)
        • [운영체제] (4)
      • 기타 (6)
      • 자격증 & 공부 (62)
        • 정보처리기사 (2)
        • SQLD (6)
        • 네트워크관리사 2급 (5)
        • 리눅스마스터 1급 (44)
        • 리눅스마스터 2급 (1)
        • ISTQB (3)
        • 시스템보안 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 태그

    Java
    자바
    pcce 기출문제
    리눅스마스터
    DB
    리눅스마스터 1급
    시큐리티
    Oracle
    springboot
    backjoon
    Flutter
    프로그래머스
    CS
    spring
    Linux
    baekjoon
    JPA
    스프링 부트 쇼핑몰 프로젝트 with JPA
    데이터
    postgresql
    python
    데이터베이스
    CS지식
    리눅스
    백준
    스프링
    스프링부트
    programmers
    Spring Security
    플러터
  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
woojin._.
[Spring Data JPA] QueryMethod
상단으로

티스토리툴바