QueryDsl 적용 가이드 (SpringBoot-gradle-멀티모듈-JPA)

spring boot2.x / gradle /jpa 환경을 가정하였습니다.

//TODO : 자세한설명추가

Plugin 추가하기

멀티모듈 프로젝트로 가정했습니다
상위 프로젝트에서 플러그인을 셋팅했습니다.

build.gradle (멀티모듈 상위 에다가 셋팅함)

1
2
3
4
5
6
7
8
9
10
ext {
springBootVersion = '2.0.5.RELEASE'
querydslPluginVersion = '1.1.7' //이부분
}
...

dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:${querydslPluginVersion}")
}

의존성 추가 / queryDSL 빌드설정 추가

queryDSL을 사용할 모듈의 build.gradle에서 셋팅

build.gradle

1
2
3
4
5
6
7
8
dependencies {
compile ("com.querydsl:querydsl-core:4.2.1")
compile ("com.querydsl:querydsl-apt:4.2.1")
compile ("com.querydsl:querydsl-jpa:4.2.1")

}

apply from: "$projectDir/queryDsl.gradle" //아래 작성한 내용 import

queryDsl.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// querydsl 적용
apply plugin: "com.ewerk.gradle.plugins.querydsl" // Plugin 적용
def querydslSrcDir = 'src/main/generated' // QClass 생성 위치

querydsl {
library = "com.querydsl:querydsl-apt"
jpa = true
querydslSourcesDir = querydslSrcDir
}

sourceSets {
main {
java {
srcDirs = ['src/main/java', querydslSrcDir]
}
}
}

QueryDsl 빌드

생성된 Entity 확인

위에서 설정한 QClass 경로에 잘 생성되었는지 확인
src/main/generated

소스코드작성

XXXRepogitoryCustom, XXXRepogitoryCustomImpl 작성

queryDSL로 짜고싶은 쿼리를 사용할 인터페이스

XXXRepogitoryCustom

1
2
3
public interface BrandRepositoryCustom {
Collection<Brand> findAllBrand();
}

구현체 작성
XXXRepogitoryCustomImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class BrandRepositoryCustomImpl extends QuerydslRepositorySupport implements BrandRepositoryCustom {

QBrand brand = QBrand.brand;
QBrandPinPolicy brandPinPolicy = QBrandPinPolicy.brandPinPolicy;
QBrandMerchant brandMerchant = QBrandMerchant.brandMerchant;

public BrandRepositoryCustomImpl() {
super(Brand.class);
}

public Collection<Brand> findAllBrand() {

return from(brand)
.innerJoin(brand.brandPinPolicy, brandPinPolicy)
.fetchJoin()
.leftJoin(brand.brandMerchant, brandMerchant)
.fetchJoin()
.fetch();
}
}

JPA repogitory에서 상속

1
2
3
4
public interface BrandRepository extends JpaRepository<Brand, String>, BrandRepositoryCustom {

Brand findBrandByBrandCode(String brandCode);
}

로직에서 사용하기

1
2
3
public Collection<Brand> getBrandAll() {
return new LinkedHashSet<>(brandRepository.findAllBrand());
}

구조

1
2
3
4
5
6
7
8
9
10
11
12
interface XXXXRepository
interface XXXXRepositoryCustom
interface JpaRepository
class XXXXRepositoryImpl
class XXXXService

XXXXRepository <|- JpaRepository : extends
XXXXRepository <|- XXXXRepositoryCustom : extends
XXXXRepositoryCustom --> XXXXRepositoryImpl : implments

XXXXService <-- XXXXRepository : DI

Comments