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 ๊ฐ์ฒด๋ก๋ถํฐ ์ ๋ ฌ ๋ฐ ํ์ด์ง ์ ๋ณด๋ฅผ ์ ์ฉํด ์ฟผ๋ฆฌ๋ฅผ ์คํํ๋ค.
์ฌ์ค ์์ง๋ ํฌ๊ฒ ๊ฐ์ด ์ ์์จ๋คโฆ ์ค์ตํ๋ฉด์ ์ต์ํด์ ธ์ผ๊ฒ ๋ค