Post

[Querydsl] Fetch

๐Ÿ“Œ ๋“ค์–ด๊ฐ€๋ฉฐ

์ด๋ฒˆ ๊ธ€์—์„œ๋Š” QueryDSL์—์„œ ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” fetch ๊ณ„์—ด ๋ฉ”์†Œ๋“œ๋“ค์„ ์ •๋ฆฌํ•œ๋‹ค. ์ƒํ™ฉ์— ๋งž๋Š” fetch๋ฅผ ๊ณจ๋ผ ์“ฐ๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค.


1. fetch ๋ฉ”์†Œ๋“œ์˜ ์ข…๋ฅ˜

๋ฉ”์†Œ๋“œ๋ฐ˜ํ™˜ํŠน์ง•
fetch()List<T>๊ธฐ๋ณธ, ์—ฌ๋Ÿฌ ๊ฒฐ๊ณผ
fetchOne()T๋‹จ์ผ ๊ฒฐ๊ณผ (์—†๊ฑฐ๋‚˜ ์—ฌ๋Ÿฟ์ด๋ฉด ์˜ˆ์™ธ)
fetchFirst()T์ฒซ ๊ฒฐ๊ณผ (์—†์œผ๋ฉด null)
fetchResults()QueryResults<T>๊ฒฐ๊ณผ + ์ „์ฒด ๊ฐœ์ˆ˜ (ํŽ˜์ด์ง•)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// fetch() โ€” ๋ฆฌ์ŠคํŠธ
List<Product> products = queryFactory
    .selectFrom(product).where(product.price.gt(1000)).fetch();

// fetchOne() โ€” ๋‹จ์ผ (0๊ฐœ/2๊ฐœโ†‘ ์‹œ ์˜ˆ์™ธ)
Product one = queryFactory
    .selectFrom(product).where(product.id.eq(1L)).fetchOne();

// fetchFirst() โ€” ์ฒซ ๊ฒฐ๊ณผ (์—†์œผ๋ฉด null)
Product first = queryFactory
    .selectFrom(product).where(product.category.eq("Electronics")).fetchFirst();

// fetchResults() โ€” ๊ฒฐ๊ณผ + ์ „์ฒด ๊ฐœ์ˆ˜
QueryResults<Product> results = queryFactory
    .selectFrom(product).where(product.price.between(500, 1000)).fetchResults();
List<Product> list = results.getResults();
long total = results.getTotal();

๐Ÿ“Œ ์‚ฌ์šฉ๋ฒ•๊ณผ ์ฃผ์˜์‚ฌํ•ญ

์ƒํ™ฉ์„ ํƒ
์—ฌ๋Ÿฌ ๊ฒฐ๊ณผfetch()
๋ฐ˜๋“œ์‹œ ํ•˜๋‚˜fetchOne() (์˜ˆ์™ธ ์ฃผ์˜)
์žˆ์„ ์ˆ˜๋„ ์—†์„ ์ˆ˜๋„fetchFirst()
ํŽ˜์ด์ง• (์ „์ฒด ๊ฐœ์ˆ˜ ํ•„์š”)fetchResults()

โš ๏ธ fetch๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋ฉ”๋ชจ๋ฆฌ๋กœ ๋กœ๋”ฉํ•˜๋ฏ€๋กœ ๋Œ€๋Ÿ‰ ๋ฐ์ดํ„ฐ๋Š” ์„ฑ๋Šฅ์„ ๊ณ ๋ คํ•ด์•ผ ํ•œ๋‹ค. ์—ฐ๊ด€ ์—”ํ‹ฐํ‹ฐ๋ฅผ ํ•จ๊ป˜ ๋กœ๋”ฉํ•˜๋ ค๋ฉด join(fetch join)์„ ํ™œ์šฉํ•œ๋‹ค.


๐Ÿ“ ์ •๋ฆฌ

1
2
3
4
5
QueryDSL fetch
โ”œโ”€ fetch()         List ๋ฐ˜ํ™˜
โ”œโ”€ fetchOne()      ๋‹จ์ผ (์—†๊ฑฐ๋‚˜ ์—ฌ๋Ÿฟ โ†’ ์˜ˆ์™ธ)
โ”œโ”€ fetchFirst()    ์ฒซ ๊ฒฐ๊ณผ (์—†์œผ๋ฉด null)
โ””โ”€ fetchResults()  ๊ฒฐ๊ณผ + ์ „์ฒด ๊ฐœ์ˆ˜ (ํŽ˜์ด์ง•)
๋ฉ”์†Œ๋“œํ•œ ์ค„ ์ •์˜
fetch์—ฌ๋Ÿฌ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ
fetchOne์ •ํ™•ํžˆ ํ•˜๋‚˜
fetchFirst์ฒซ ๊ฒฐ๊ณผ(์—†์œผ๋ฉด null)
fetchResults๊ฒฐ๊ณผ+๊ฐœ์ˆ˜

fetch ๋ฉ”์†Œ๋“œ๋Š” โ€œ๊ฒฐ๊ณผ๊ฐ€ ๋ช‡ ๊ฐœ์ธ๊ฐ€, ๊ฐœ์ˆ˜๊ฐ€ ํ•„์š”ํ•œ๊ฐ€โ€์— ๋”ฐ๋ผ ๊ณจ๋ผ ์“ด๋‹ค. ํŠนํžˆ fetchOne()์€ ๊ฒฐ๊ณผ๊ฐ€ 0๊ฐœ๋‚˜ 2๊ฐœ ์ด์ƒ์ด๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋‚˜๋ฏ€๋กœ, ํ™•์‹คํ•  ๋•Œ๋งŒ ์‚ฌ์šฉํ•˜์ž.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.