springframework/Spring Data JPA

Spring Data JPA : Query By Example

Jungsoomin :) 2020. 11. 19. 17:47
  • 계륵 같은 녀석으로 알고 있으면 좋을만한 기능
  • 조건 조합을 유연하게 가져가지 못함

Example = Prove + ExampleMatcher

  • Prove 는 도메인 객체를 의미함
  • ExampleMatcher 는 Prove 와 DB 데이터 매칭을 관리
  • 기본적으로는 DB 데이터가 Entity 데이터와 정확히 일치해야한다.

Example 의 정적메서드 of 로 Example 을 만든다.

  • ExampleMatcher 를 이용해서 조건을 만든다.
  • Entity 인 prove, ExampleMatcher 를 매개 값으로 Example 의 정적메서드 .of() 를 호출하여 Example<Domin> 을 만든다.
  • 사용할 리포지토리는 QueryByExampleExecutor<Domain> 을 상속해야한다.
public interface CommentRepository extends JpaRepository<Comment,Long>, JpaSpecificationExecutor<Comment>, QueryByExampleExecutor<Comment> {
}

//
@Test
    public void qbe(){
        Comment prove = new Comment();
        prove.setBest(true);

        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withIgnoreNullValues();

        Example<Comment> example = Example.of(prove, exampleMatcher);
        List<Comment> all = commentRepository.findAll(example);
    }

///
Hibernate: 
    select
        comment0_.id as id1_1_,
        comment0_.best as best2_1_,
        comment0_.comment as comment3_1_,
        comment0_.down as down4_1_,
        comment0_.post_id as post_id7_1_,
        comment0_.title as title5_1_,
        comment0_.up as up6_1_ 
    from
        comment comment0_ 
    where
        comment0_.best=? 
        and comment0_.up=0 
        and comment0_.down=0
2020-11-19 17:38:42.460 TRACE 13048 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BOOLEAN] - [true]

 

...어, ..음. 쓰라면 QueryDSL 이나 Specification 쓰고 싶다.

'springframework > Spring Data JPA' 카테고리의 다른 글

Spring Data JPA : Auditing, Life Cycle Event  (0) 2020.11.19
Spring Data JPA : Transaction  (0) 2020.11.19
Spring Data JPA : Specifications  (0) 2020.11.19
Spring Data JPA : Projection  (0) 2020.11.19
Spring Data JPA : Entity Graph  (0) 2020.11.19