@Query 사용하기 5 / 패스트캠퍼스 챌린지 26일차

망고쥬스·2021년 11월 26일
0
post-thumbnail

페이징 기능

JPA > PagingAndSortingRepository
Pageable 방식의 pageable를 리턴하게 된다.

Page<BookNameAndCategory> findBookNameAndCategory(Pageable pageable);

BookRepositoryTest

//Pageable은 PageRequest라는 구현체가 존재한다. (페이지, 사이즈) -> 1페이지당 1개의 데이터를 가져온다 로 설정
bookRepository.findBookNameAndCategory(PageRequest.of(1,1)).forEach(
	bookNamdAndCategory -> System.out.println(bookNameAndCategory.getCategory()+" : "+ bookNameAndCategory.getCategory()));
}

Result (id=2 출력) :


bookRepository.findBookNameAndCategory(PageRequest.of(0,1)).forEach(
	bookNamdAndCategory -> System.out.println(bookNameAndCategory.getCategory()+" : "+ bookNameAndCategory.getCategory()));
}

Result (id=1 출력):


Native Query 활용하기

  • 성능에 대한 문제를 해결하기 위해 NativeQuery를 사용한다
    -- update 쿼리처럼 각각의 id를 이용해

매우중요

NativeQuery의 경우 Entity속성을 사용하지 못한다
즉 entity이름이 아닌 테이블 이름이 from절에 삽입되어야 한다.
컬럼 또한 실제 테이블에 적용되어 있는 이름으로 입력을 해 주어야 한다.

BookRepository

@Query(value = "select * from book", nativeQuery = true)
List<Book> findAllCustom();

BookRepositoryTest

@Test
void nativeQueryTest(){
	bookRepository.findAll().forEach(System.out::println);
	bookRepository.findAllCustom().forEach(System.out::println);
}

RESULT

: native쿼리의 경우 @Where 어노테이션이 작동하지 않는다. 해서 단순하게 select * from book 그 자체만 사용하는것.
  • findAll()
    Book(super=BaseEntity(createdAt=2021-06-09T20:41:59:450565, updatedAt=2021-06-09T20:41:59,450654), id=1,isDeleted=false, ...
    Book(super=BaseEntity(createdAt=2021-06-09T20:41:59:450565, updatedAt=2021-06-09T20:41:59,450654), id=2,isDeleted=false, ...
  • findAllCustom() - nativeQuery (@Where(caluse = isDeleted=false) 적용되지 않고 검색된다)
    Book(super=BaseEntity(createdAt=2021-06-09T20:41:59:450565, updatedAt=2021-06-09T20:41:59,450654), id=1,isDeleted=false, ...
    Book(super=BaseEntity(createdAt=2021-06-09T20:41:59:450565, updatedAt=2021-06-09T20:41:59,450654), id=2,isDeleted=false, ...
    Book(super=BaseEntity(createdAt=2021-06-09T20:41:59:450565, updatedAt=2021-06-09T20:41:59,450654), id=3,isDeleted=true, ...

 ? 


#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #한번에끝내는Java/Spring웹개발마스터초격차패키지Online

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

https://bit.ly/3FVdhDa

profile
#newbieDeveloper #since 2021.04.06

0개의 댓글