[인프런 김영한] JPA - 페이징

2021. 2. 16. 13:35프로그래밍 언어/Spring Framework

[인프런 김영한] JPA - 페이징


해당 글은 인프런 김영한강사님의 영상을 보고 정리한 글입니다.

김영한 인프런 : www.inflearn.com/users/@yh

 

인프런 - 김영한의 강의들을 만나보세요.

우아한형제들 개발 팀장 (전: 카카오, SK플래닛) 저서: 자바 ORM 표준 JPA 프로그래밍

www.inflearn.com


▣ 페이징 API

 

* JPA는 페이징을 다음 두 API로 추상화

 - setFirstResult(int startPosition) : 조회 시작 위치 (0부터 시작)

 - setMaxResults(int maxResult) : 조회할 데이터 수

 

 

▣ 실습

for (int i = 0; i < 100; i++) {
  Member member = new Member();
  member.setUsername("member" + i);
  member.setAge(i);
  em.persist(member);
}

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

List<Member> resultList = em.createQuery("select m from Member m order by m.age desc", Member.class)
  .setFirstResult(0)
  .setMaxResults(10)
  .getResultList();

System.out.println("resultList.size = " + resultList.size());
  for (Member member1 : resultList) {
  System.out.println("member1 = " + member1);
}


// 결과
Hibernate: 
    /* select
        m 
    from
        Member m 
    order by
        m.age desc */ select
            member0_.id as id1_0_,
            member0_.age as age2_0_,
            member0_.TEAM_ID as team_id4_0_,
            member0_.username as username3_0_ 
        from
            Member member0_ 
        order by
            member0_.age desc limit ?
resultList.size = 10
member1 = Member{id=100, username='member99', age=99}
member1 = Member{id=99, username='member98', age=98}
member1 = Member{id=98, username='member97', age=97}
member1 = Member{id=97, username='member96', age=96}
member1 = Member{id=96, username='member95', age=95}
member1 = Member{id=95, username='member94', age=94}
member1 = Member{id=94, username='member93', age=93}
member1 = Member{id=93, username='member92', age=92}
member1 = Member{id=92, username='member91', age=91}
member1 = Member{id=91, username='member90', age=90}

 

* 각각의 DB에 따라서 쿼리가 조금씩 다름.