QueryDsl 사용하기.



이번에 QueryDsl 을 사용할 기회와 필요성이 있어 적용하고 사용해봤습니다.

그 과정이 쉽지는 않다는 것을 느꼈기에 정리하고자 합니다.


우선 QueryDsl 을 사용하기 위해 dependency 를 추가할때 어떤 글은 com.querydsl 이고 어떤 글은 com.mysema.querydsl 으로 나와있습니다.

이유는 QueryDsl 이 4.x 버전으로 올라가며 package 명이 바뀌어서 그 이전글은 그대로 남아 있는 것으로 생각됩니다.


처음으로 build.gradle 파일에 아래와 같이 내용을 써줍니다.



dependencies {
compile("mysql:mysql-connector-java")
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile ("com.querydsl:querydsl-core")
compile ("com.querydsl:querydsl-apt")
compile ("com.querydsl:querydsl-jpa")
testCompile group: 'junit', name: 'junit', version: '4.12'
}

sourceSets {
main {
java {
srcDirs 'src/main/java', 'src/main/generated'
}
}
}

task generateQueryDSL(type: JavaCompile, group: 'build', description: 'Generates the QueryDSL query types') {
file(new File(projectDir, "/src/main/generated")).deleteDir()
file(new File(projectDir, "/src/main/generated")).mkdirs()
source = sourceSets.main.java
classpath = configurations.compile + configurations.compileOnly
options.compilerArgs = [
"-proc:only",
"-processor", "com.querydsl.apt.jpa.JPAAnnotationProcessor",
"-processor", 'com.querydsl.apt.jpa.JPAAnnotationProcessor,lombok.launch.AnnotationProcessorHider$AnnotationProcessor'
]
destinationDir = file('src/main/generated')
}

compileJava {
dependsOn generateQueryDSL
}

clean.doLast {
file(new File(projectDir, "/src/main/generated")).deleteDir()
}



위에서 clean.doLast 라는 부분이 의아하실 것 같은데 컴파일할 때 이전에 생성되었던 Q Class 가 남아있다면 에러를 발생시키기 때문에 이를 방지하기 위해 clean.doLast 에서 지우고 있습니다.





위 사진에 보이는 Tasks - application - bootRun 을 실행하면 





위와 같이 지정한 위치에 안에는 Q Class 들이 들어가 있는 상태의 generated 폴더가 생성됩니다.

이젠 CustomRepository 와 CustomRepositoryImpl 을 만들어야 합니다.



public interface CustomTestRepository {
Page<Test> findTestBySearchFilter(Long testId, SearchOptions searchOptions, Pageable pageable);

}



@Component
public class TestRepositoryImpl extends QueryDslRepositorySupport implements CustomTestRepository {

public TestRepositoryImpl() {
super(Test.class);
}

@Override
public Page<Test> findTestBySearchFilter(Long testId, SearchOptions searchOptions, Pageable pageable) {
QTest qTest = QTest.test;
JPQLQuery query = from(qTest);

if(testId != null) {
query.where(qTest.testId.eq(testId));
}

do something...

final List<Test> tests = getQuerydsl().applyPagination(pageable, query).fetch();
final long totalCount = query.fetchCount();

return new PageImpl<>(tests, pageable, totalCount);
}



위의 코드는 예시로 필요에 따라 추가, 수정하여 사용하면 됩니다.





'Database > QueryDsl' 카테고리의 다른 글

QueryDsl like 와 contains 의 차이  (0) 2018.08.13

+ Recent posts