QueryDsl ์ด๋ž€?

์ •์  ํƒ€์ž…์„ ์‚ฌ์šฉํ•ด์„œ SQL๊ณผ ๊ฐ™์€ ์ฟผ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ฃผ๋Š” ํ”„๋ ˆ์ž„์›Œํฌ

์‚ฌ์šฉํ•˜๋Š” ์ด์œ ?

์ƒํ’ˆ ๊ฒ€์ƒ‰์„ ํ•˜๋ ค๊ณ  ํ•œ๋‹ค. ์ด๋ฆ„, ์„ค๋ช…, ๊ฐ€๊ฒฉ, ์ˆ˜๋Ÿ‰์ด ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์„ ๋•Œ, ์กฐ๊ฑด ๊ฒ€์ƒ‰์„ ์œ„ํ•ด ์ด๋ฆ„, ์„ค๋ช…, ๊ฐ€๊ฒฉ, ์ˆ˜๋Ÿ‰์„ ๊ฒ€์ƒ‰ํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ, ์ด๋ฆ„+์„ค๋ช…, ์„ค๋ช…+๊ฐ€๊ฒฉ, ๊ฐ€๊ฒฉ+์ˆ˜๋Ÿ‰ ๋“ฑ๋“ฑ.. ์˜ ์กฐ๊ฑด์ด ๋Š˜์–ด๋‚˜๊ฒŒ ๋˜๋ฉด ๊ทธ๋งŒํผ if๋ฌธ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๊ณ  ๊ทธ๋งŒํผ ์ฟผ๋ฆฌ๊ฐ€ ๋ณต์žกํ•ด์ง„๋‹ค.

์ด๋•Œ QueryDsl์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•ด ์‰ฝ๊ฒŒ ๋™์  ๊ฒ€์ƒ‰์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‹ค๋ฅธ ๊ณณ์—๋„ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ํ•˜์ง€๋งŒ ์—ฌ๊ธฐ์„  ์•Œ์•„๋ณด์ง€ ๋ง์ž)

QueryDSL ์„ค์ •

ext {
    set('springCloudVersion', "2023.0.2")
    set('querydslVersion', "5.0.0")  // QueryDSL ๋ฒ„์ „ ๋ช…์‹œ์ ์œผ๋กœ ์„ค์ •
}

dependencies {
	implementation "com.querydsl:querydsl-jpa:${querydslVersion}:jakarta"
	annotationProcessor "com.querydsl:querydsl-apt:${querydslVersion}:jakarta"
	annotationProcessor "jakarta.annotation:jakarta.annotation-api"
	annotationProcessor "jakarta.persistence:jakarta.persistence-api"

	...
}

def querydslSrcDir = 'src/main/generated'
clean {
    delete file(querydslSrcDir)
}
tasks.named('test') { useJUnitPlatform() }

build.gradle์— denpendency๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  QueryDsl ๋ฒ„์ „๊ณผ ์ €์žฅ๋  ์œ„์น˜๋ฅผ ์ง€์ •ํ•ด์ค€๋‹ค

QueryResults<Product> results = queryFactory
    .selectFrom(product)
    .where(
        nameContains(searchDto.getName()),
        descriptionContains(searchDto.getDescription()),
        priceBetween(searchDto.getMinPrice(), searchDto.getMaxPrice()),
        quantityBetween(searchDto.getMinQuantity(), searchDto.getMaxQuantity())
    )
    .orderBy(orders.toArray(new OrderSpecifier[0]))
    .offset(pageable.getOffset())
    .limit(pageable.getPageSize())
    .fetchResults();
private BooleanExpression nameContains(String name) {
    return name != null ? product.name.containsIgnoreCase(name) : null;
}

QueryDSL์˜ BooleanExpression์„ ์‚ฌ์šฉํ•˜์—ฌ ๋™์  where์„ ๊ตฌ์„ฑํ•˜๊ณ  Pageable ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ ์ •๋ ฌ ๋ฐ ํŽ˜์ด์ง• ์ •๋ณด๋ฅผ ์ ์šฉํ•ด ์ฟผ๋ฆฌ๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.

์‚ฌ์‹ค ์•„์ง๋„ ํฌ๊ฒŒ ๊ฐ์ด ์ž˜ ์•ˆ์˜จ๋‹คโ€ฆ ์‹ค์Šตํ•˜๋ฉด์„œ ์ต์ˆ™ํ•ด์ ธ์•ผ๊ฒ ๋‹ค