실전! 스프링 데이터 JPA

Ch06. 나머지 기능들 - Query By Example

webmaster 2021. 12. 28. 13:35
728x90

JPARepository를 Extends 받으면 사용이 가능하다.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example

 

Spring Data JPA - Reference Documentation

Example 109. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del

docs.spring.io

QueryByExample 테스트

  • Probe: 필드에 데이터가 있는 실제 도메인 객체
  • ExampleMatcher: 특정 필드를 일치시키는 상세한 정보 제공, 재사용 가능
  • Example: Probe와 ExampleMatcher로 구성, 쿼리를 생성하는 데 사용
  • 장점 
    • 동적 쿼리를 편리하게 처리
    • 도메인 객체를 그대로 사용
    • 데이터 저장소를 RDB에서 NOSQL로 변경해도 코드 변경이 없게 추상화 되어 있음
    • 스프링 데이터 JPA JpaRepository 인터페이스에 이미 포함
  • 단점
    • 조인은 가능하지만 내부 조인(INNER JOIN)만 가능함 외부 조인(LEFT JOIN) 안됨
    • 다음과 같은 중첩 제약조건 안됨
      • firstname = ?0 or (firstname = ?1 and lastname = ?2)
    • 매칭 조건이 매우 단순함
      • 문자는 starts/contains/ends/regex
      • 다른 속성은 정확한 매칭( = )만 지원

실무에서 사용하기에는 매칭 조건이 너무 단순하고, leftJoin이 안됨

실무에서는 QueryDSL을 사용하자

728x90