Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

쿼리 메서드 본문

인프런/[인프런] Spring Data JPA

쿼리 메서드

Seung__ 2021. 8. 28. 11:42

1. Query Method의 기능


  • 메소드 이름으로 쿼리 생성
  • NamedQuery
  • @Query - 리파지토리 메소드에 쿼리 정의
  • 파라미터 바인딩
  • 반환 타입
  • 페이징과 정렬
  • 벌크성 수정 쿼리
  • @EntityGraph

 

2. 메소드 이름으로 쿼리 생성


  • 메소드 이름을 분석해서 JPQL 쿼리 실행
  • 이름과 나이를 기준으로 회원을 조회하려면?
  • 먼저 JPA로 짜보자
 public List<Member> findMemberByUserNameAndAgeGreaterThan(String userName, int age){
        return em.createQuery("select m from Member m where m.userName = :userName and m.age > :age")
                .setParameter("userName", userName)
                .setParameter("age", age)
                .getResultList();
    }
 @Test
    public void findByUserNameAndAgeGreaterThan(){
        Member member1 = new Member("aaa", 10);
        Member member2 = new Member("bbb", 20);
        memberJpaRepository.save(member1);
        memberJpaRepository.save(member2);

        List<Member> findMembers = memberJpaRepository.findMemberByUserNameAndAgeGreaterThan("bbb", 10);

        Assertions.assertThat(findMembers.get(0).getUserName()).isEqualTo(member2.getUserName());
        Assertions.assertThat(findMembers.get(0).getAge()).isEqualTo(member2.getAge());
        
    }

흠 잘 된다 ㅋㅋㅋㅋ

 

근데 일일히 JPQL짜기 귀찮은데.......

 

  • SpringdataJPA활용
public interface MemberRepository extends JpaRepository<Member, Long> {

    public List<Member> findMemberByUserNameAndAgeGreaterThan(String userName, int age);

}

 이렇게만 해줘도... 알아서 구현체 만들어줌... 

 @Test
    public void findByUserNameAndAgeGreaterThan(){
        Member member1 = new Member("aaa", 10);
        Member member2 = new Member("bbb", 20);
        memberRepository.save(member1);
        memberRepository.save(member2);

        List<Member> findMembers = memberRepository.findMemberByUserNameAndAgeGreaterThan("bbb", 10);

        Assertions.assertThat(findMembers.get(0).getUserName()).isEqualTo(member2.getUserName());
        Assertions.assertThat(findMembers.get(0).getAge()).isEqualTo(member2.getAge());

    }

쿼리가 날라간거도 확인 가능하다.

    select
        member0_.member_id as member_i1_0_,
        member0_.age as age2_0_,
        member0_.team_id as team_id4_0_,
        member0_.user_name as user_nam3_0_ 
    from
        member member0_ 
    where
        member0_.user_name=? 
        and member0_.age>?

 

  • 쿼리 메서드 필터 조건
 

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

 

 

 

3. 스프링 데이터 JPA가 제공하는 쿼리 메서드 기능


  • 조회: find…By ,read…By ,query…By get…By,
    • #repositories.query-methods.query-creation
    • 예:) findHelloBy 처럼 ...에 식별하기 위한 내용(설명)이 들어가도 된다.
    • By뒤에 조건 없으면 전체 조회
  • COUNT: count…By 반환타입 long
  • EXISTS: exists…By 반환타입 boolean
  • 삭제: delete…By, remove…By 반환타입 long
  • DISTINCT: findDistinct, findMemberDistinctBy
  • LIMIT: findFirst3, findFirst, findTop, findTop3
    • #repositories.limit-query-result
 

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

 

주의! : 엔티티의 필드명이 변경되면 인터페이스에 정의한 메서드 이름도 꼭 함께 변경해야 한다.

그렇지 않으면 애플리케이션을 시작하는 시점에 오류가 발생한다.

 

4. GitHub : 210828 QueryMethod


 

GitHub - bsh6463/SpringDataJpa

Contribute to bsh6463/SpringDataJpa development by creating an account on GitHub.

github.com

 

Comments