Skip to content

Commit

Permalink
[Week9][Chap4] Feat: 순수 JPA 페이징과 정렬 (#106)
Browse files Browse the repository at this point in the history
  • Loading branch information
jyjyjy25 committed Nov 21, 2023
1 parent 5a99022 commit 8003792
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,18 @@ public List<Member> findByUsername(String username) {
.setParameter("username", username)
.getResultList();
}

public List<Member> findByPage(int age, int offset, int limit) {
return em.createQuery("select m from Member m where m.age = :age order by m.username desc")
.setParameter("age", age)
.setFirstResult(offset)
.setMaxResults(limit)
.getResultList();
}

public long totalCount(int age) {
return em.createQuery("select count(m) from Member m where m.age = :age", Long.class)
.setParameter("age", age)
.getSingleResult();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,30 @@ public void testNamedQuery() {
Member findMember = result.get(0);
assertThat(findMember).isEqualTo(m1);
}

@Test
public void paging() {
// given
memberJpaRepository.save(new Member("member1", 10));
memberJpaRepository.save(new Member("member2", 10));
memberJpaRepository.save(new Member("member3", 10));
memberJpaRepository.save(new Member("member4", 10));
memberJpaRepository.save(new Member("member5", 10));

int age = 10;
int offset = 0;
int limit = 3;

// when
List<Member> members = memberJpaRepository.findByPage(age, offset, limit);
long totalCount = memberJpaRepository.totalCount(age);

// 페이지 계산 공식 적용
// totalPage = totalCount / size

// then
assertThat(members.size()).isEqualTo(3);
assertThat(totalCount).isEqualTo(5);

}
}

0 comments on commit 8003792

Please sign in to comment.