Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
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
관리 메뉴

개발자되기 프로젝트

Native Query 본문

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

Native Query

Seung__ 2021. 9. 1. 20:10

1. Native Query


  • 가급적 네이티브 쿼리는 사용하지 않는게 좋음, 정말 어쩔 수 없을 때 사용
  • 최근에 나온 궁극의 방법 --> 스프링 데이터 Projections 활용
  • Repository
@Query(value = "select * from member where userName = ?", nativeQuery = true)
Member findByNativeQuery(String userName);
  • Test
Member result = memberRepository.findByNativeQuery("m1");
System.out.println("result = " + result);
  • SQL
    select
        * 
    from
        member 
    where
        user_name = ?

 

2. 스프링 데이터 JPA 기반 네이티브 쿼리

  • 페이징 지원
  • 반환 타입
    • Object[]
    • Tuple
    • DTO(스프링 데이터 인터페이스 Projections 지원)
  • 제약
    • Sort 파라미터를 통한 정렬이 정상 동작하지 않을 수 있음(믿지 말고 직접 처리)
    • JPQL처럼 애플리케이션 로딩 시점에 문법 확인 불가
    • 동적 쿼리 불가

 

3. Projections 활용

  • Interface
public interface MemberProjection {

    Long getId();
    String getUserName();
    String getTeamName();

}
  • Repository
 @Query(value = "select m.member_id as id, m.userName, t.name as teamName " +
            "from member m left join team t",
    countQuery = "select count(*) from member",
    nativeQuery = true)
    Page<MemberProjection> findByNativeProjection(Pageable pageable);
  • Test
   @Test
    public void nativeQuery(){
        Team teamA = new Team("teamA");
        em.persist(teamA);

        Member m1 = new Member("m1", 0, teamA);
        Member m2 = new Member("m2", 0, teamA);
        em.persist(m1);
        em.persist(m2);

        em.flush();
        em.clear();

        //when
        Page<MemberProjection> result = memberRepository.findByNativeProjection(PageRequest.of(0, 10));
        List<MemberProjection> content = result.getContent();
        for (MemberProjection memberProjection : content) {
            System.out.println("memberProjection.getUserName() = " + memberProjection.getUserName());
            System.out.println("memberProjection.getTeamName() = " + memberProjection.getTeamName());
        }
    }

 

 

4. 동적 네이티브 쿼리


하이버네이트를 직접 활용
스프링 JdbcTemplate, myBatis, jooq같은 외부 라이브러리 사용

 

 

5.GitHub : 210901 NativeQuery


 

GitHub - bsh6463/SpringDataJpa

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

github.com

 

'인프런 > [인프런] Spring Data JPA' 카테고리의 다른 글

Projections  (0) 2021.08.31
Query By Example  (0) 2021.08.31
SpringDataJpa의 구현체  (0) 2021.08.31
Web 확장 : 도메인 클래스 컨버터, 페이징 & 정렬  (0) 2021.08.31
Auditing  (0) 2021.08.30
Comments