Post

[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.