Post

[Querydsl] Q-ํƒ€์ž…(Q-type)

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

์ด๋ฒˆ ๊ธ€์—์„œ๋Š” QueryDSL์˜ ํ•ต์‹ฌ์ธ Q-Type์„ ์ •๋ฆฌํ•œ๋‹ค.

QueryDSL์ด๋ž€? ์ž๋ฐ” ๊ธฐ๋ฐ˜์˜ ์˜คํ”ˆ์†Œ์Šค SQL ํ”„๋กœ์ ์…˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ JPAยทHibernate๋ฅผ ์ง€์›ํ•œ๋‹ค. Q-Type์ด๋ž€? ์—”ํ‹ฐํ‹ฐ์˜ ํ•„๋“œ๋ฅผ ์ •์  ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•œ ํด๋ž˜์Šค. ์ฟผ๋ฆฌ ์ž‘์„ฑ ์‹œ ํƒ€์ž… ์•ˆ์ „์„ฑ์„ ์ œ๊ณตํ•œ๋‹ค.


1. Q-Type ์‚ฌ์šฉํ•˜๊ธฐ

Product ์—”ํ‹ฐํ‹ฐ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•˜์ž.

1
2
3
4
5
6
7
8
@Entity
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private int price;
    private String category;
}

์ž๋™ ์ƒ์„ฑ๋œ QProduct.product๋กœ ํƒ€์ž… ์•ˆ์ „ํ•œ ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•œ๋‹ค.

1
2
3
4
5
6
7
8
import static com.example.model.QProduct.product;

public List<Product> findProductsInCategory(String category) {
    return new JPAQueryFactory(entityManager)
        .selectFrom(product)
        .where(product.category.eq(category))   // ํ•„๋“œ ์ ‘๊ทผ ์‹œ ์˜คํƒ€ ๋ฐฉ์ง€
        .fetch();
}

๐Ÿ’ก product.category.eq(category)์ฒ˜๋Ÿผ ํ•„๋“œ์— ์ ‘๊ทผํ•˜๋ฉด, ๋ฌธ์ž์—ด JPQL๊ณผ ๋‹ฌ๋ฆฌ ์ปดํŒŒ์ผ ์‹œ์ ์— ์˜คํƒ€๋ฅผ ์žก์•„์ค€๋‹ค. ์ด๊ฒƒ์ด QueryDSL์˜ ๊ฐ€์žฅ ํฐ ์žฅ์ ์ธ ํƒ€์ž… ์•ˆ์ „์„ฑ์ด๋‹ค.

๋ฐฉ์‹์˜คํƒ€ ๊ฒ€์ถœ
๋ฌธ์ž์—ด JPQL๋Ÿฐํƒ€์ž„์— ๋ฐœ๊ฒฌ
Q-Type์ปดํŒŒ์ผ ์‹œ์ ์— ๋ฐœ๊ฒฌ

๐Ÿ“Œ ์ฃผ์˜์‚ฌํ•ญ๊ณผ ํŒ

ํ•ญ๋ชฉ๋‚ด์šฉ
๋นŒ๋“œ ์‹œ ์ƒ์„ฑ ํ™•์ธQ-Type์€ ์ฝ”๋“œ ์ƒ์„ฑ์œผ๋กœ ๋งŒ๋“ค์–ด์ง โ†’ ๋นŒ๋“œ ํ›„ ํ™•์ธ
์—”ํ‹ฐํ‹ฐ์™€ ์ผ์น˜Q-Type ํ•„๋“œ๋Š” ์—”ํ‹ฐํ‹ฐ ํ•„๋“œ์™€ ์ผ์น˜ํ•ด์•ผ ํ•จ
์ž๋™ ์™„์„ฑ ํ™œ์šฉIDE ์ž๋™์™„์„ฑ์œผ๋กœ ๋น ๋ฅด๊ณ  ์ •ํ™•ํ•˜๊ฒŒ

๐Ÿ“ ์ •๋ฆฌ

1
2
3
4
5
QueryDSL Q-Type
โ”œโ”€ ์ •์ฒด    ์—”ํ‹ฐํ‹ฐ ํ•„๋“œ๋ฅผ ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•œ ํด๋ž˜์Šค
โ”œโ”€ ์‚ฌ์šฉ    QProduct.product.category.eq(...)
โ”œโ”€ ์žฅ์     ํƒ€์ž… ์•ˆ์ „์„ฑ (์ปดํŒŒ์ผ ์‹œ ์˜คํƒ€ ๊ฒ€์ถœ)
โ””โ”€ ์ƒ์„ฑ    ๋นŒ๋“œ ์‹œ ์ž๋™ ์ƒ์„ฑ
๊ฐœ๋…ํ•œ ์ค„ ์ •์˜
QueryDSLํƒ€์ž… ์•ˆ์ „ํ•œ ์ฟผ๋ฆฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
Q-Type์—”ํ‹ฐํ‹ฐ ํ•„๋“œ๋ฅผ ์ƒ์ˆ˜ํ™”ํ•œ ํด๋ž˜์Šค
ํƒ€์ž… ์•ˆ์ „์„ฑ์ปดํŒŒ์ผ ์‹œ์  ์˜คํƒ€ ๊ฒ€์ถœ

Q-Type์€ QueryDSL์˜ ์‹ฌ์žฅ์ด๋‹ค. ๋ฌธ์ž์—ด ์ฟผ๋ฆฌ์˜ ์˜คํƒ€ ์œ„ํ—˜์„ ์ปดํŒŒ์ผ ์‹œ์ ์— ์ œ๊ฑฐํ•ด์ฃผ๋‹ˆ, ๋ณต์žกํ•œ ๋™์  ์ฟผ๋ฆฌ๋„ ์•ˆ์ „ํ•˜๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

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

Comments powered by Disqus.