반응형
JPA 게시글은 대부분 인프런의 김영한님의 강의인 '자바 ORM 표준 JPA 프로그래밍' 기반으로 내용을 정리했습니다.
페이징 API
- JPA는 페이징을 다음 두 API로 추상화한다.
- setFirstResult(int startPosition) : 조회 시작 위치 (0부터 시작)
- setMaxResult(int maxResult) : 조회할 데이터 수
setFirstResult()와 setMaxResult()는 다음과 같이 사용하면 된다.
List<Member> result = em.createQuery("select m from Member m order by m.age desc", Member.class)
.setFirstResult(0)
.setMaxResults(10)
.getResultList();
그리고 테스트를 위에 상단에 for문을 돌려 100개의 Member Data를 만든다.
for(int i = 0; i < 100; i++) {
Member member = new Member();
member.setUsername("member" + i);
member.setAge(i);
em.persist(member);
}
그러고나서 결과를 출력해보자.
System.out.println("result.size() = " + result.size());
for( Member member1 : result) {
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 ?
result.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}
페이징이 제대로 된 걸 확인할 수 있다. 페이징 쿼리는 지금 h2Database 문법에 맞게 작성 된 것이다.
persistence.xml에서 방언을 오라클로 수정해주면 오라클 SQL 문법으로 쿼리가 날라간다.
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle8iDialect"/>
Hibernate:
/* select
m
from
Member m
order by
m.age desc */ select
*
from
( 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 )
where
rownum <= ? // Oracle의 Rownum
반응형