[Querydsl] ํ์ด์ง(paging)
๐ ๋ค์ด๊ฐ๋ฉฐ
์ด๋ฒ ๊ธ์์๋ QueryDSL๋ก ํ์ด์งํ๋ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํ๋ค.
ํ์ด์ง์ด๋? ๋ฐ์ดํฐ๋ฅผ ์ผ์ ๋์ฉ ๋๋ ๊ฐ์ ธ์ค๋ ๊ฒ. ์ ์ฒด๋ฅผ ํ ๋ฒ์ ๋ก๋ฉํ์ง ์๊ณ ํ์ํ ๋งํผ๋ง ๊ฐ์ ธ์ ์ฑ๋ฅ์ ์ต์ ํํ๋ค.
1. offset๊ณผ limit
1
2
3
4
5
6
List<Product> products = queryFactory
.selectFrom(product)
.orderBy(product.price.asc())
.offset(10) // 10๋ฒ์งธ๋ถํฐ ์์
.limit(5) // 5๊ฐ์ฉ
.fetch();
| ๋ฉ์๋ | ์ญํ |
|---|---|
offset(n) | n๋ฒ์งธ๋ถํฐ ์์ (๊ฑด๋๋ฐ๊ธฐ) |
limit(m) | m๊ฐ์ฉ ๊ฐ์ ธ์ค๊ธฐ |
๐ก ํ์ด์ง ์
orderBy๋ก ์ ๋ ฌ์ ๋ช ์ํด์ผ ๋ฐ์ดํฐ ์์๊ฐ ์ผ๊ด๋๋ค.
2. fetchResults โ ์ ์ฒด ๊ฐ์๊น์ง
1
2
3
4
5
6
7
8
9
QueryResults<Product> results = queryFactory
.selectFrom(product)
.orderBy(product.price.asc())
.offset(10)
.limit(5)
.fetchResults();
List<Product> list = results.getResults(); // ํ์ฌ ํ์ด์ง ๋ฐ์ดํฐ
long total = results.getTotal(); // ์ ์ฒด ๊ฐ์
๐ก
fetchResults()๋ ํ ๋ฒ์ ํธ์ถ๋ก ๋ฐ์ดํฐ์ ์ ์ฒด ๊ฐ์๋ฅผ ํจ๊ป ๊ฐ์ ธ์, ์ ์ฒด ํ์ด์ง ์ ๊ณ์ฐ์ ์ ์ฉํ๋ค. (count ์ฟผ๋ฆฌ๊ฐ ์ถ๊ฐ๋ก ๋๊ฐ)
๐ ์ฃผ์์ฌํญ๊ณผ ํ
| ํญ๋ชฉ | ๋ด์ฉ |
|---|---|
| ์ฑ๋ฅ | offset์ด ํฐ ๊ฒฝ์ฐ ๋ค๋ก ๊ฐ์๋ก ๋๋ ค์ง ์ ์์ |
| fetchResults | ๋ฐ์ดํฐ + ์ ์ฒด ๊ฐ์ โ ํ์ด์ง ์ ๊ณ์ฐ์ ์ ์ฉ |
| ์ ๋ ฌ ๋ช ์ | ํ์ด์ง์๋ ์ ๋ ฌ์ด ํ์ |
๐ ์ ๋ฆฌ
1
2
3
4
QueryDSL ํ์ด์ง
โโ offset(n)/limit(m) ๊ฑด๋๋ฐ๊ธฐ + ๊ฐ์
โโ fetchResults() ๋ฐ์ดํฐ + ์ ์ฒด ๊ฐ์
โโ ํ์ orderBy๋ก ์ ๋ ฌ ๋ช
์
| ๊ฐ๋ | ํ ์ค ์ ์ |
|---|---|
| offset/limit | ์์ ์์น / ๊ฐ์ |
| fetchResults | ๊ฒฐ๊ณผ + ์ ์ฒด ๊ฐ์ |
ํ์ด์ง์ offsetยทlimit์ผ๋ก ๊ฐ๋จํ ๊ตฌํํ๋ค. ์ ์ฒด ํ์ด์ง ์๊ฐ ํ์ํ๋ฉด fetchResults()๋ฅผ ์ฐ๊ณ , ์์ ์ผ๊ด์ฑ์ ์ํด ํญ์ orderBy๋ฅผ ํจ๊ป ์ง์ ํ์.
This post is licensed under CC BY 4.0 by the author.
Comments powered by Disqus.