1. QueryDsl 이란?
- 오픈소스 프레임워크, JPQL을 java코드로 작성할 수 있또록 하는 라이브러리
- Jpa로 해결하기 어려운 복잡한 쿼리/동적 쿼리를 해결할 수 있음
- ★ 자바코드로 작성하기 때문에 문법오류를 컴파일 시점에 잡아낼 수 있다.
- 동적인 쿼리작성이 편리하고, IDE의 도움을 받아 제약 조건등을 메서드 추출을 통해 재사용 할 수 있다.
- select, from, where등 쿼리 작성에 필요한 키워드를 메서드 형식으로 제공한다.
2. 사용 예시
1). EntityManager 주입받기
- QueuryDsl 이 query를 생성할 수 있도록 EntityManager를 주입
@Configuration
public class QuerydslConfiguration {
@Autowired
EntityManager em;
@Bean
public JPAQueryFactory jpaQueryFactory() {
return new JPAQueryFactory(em);
}
}
2). RoomRepositoryCustom 생성 및 구현
public interface RoomRepositoryCustom {
Page<RoomOfList> searchAll(FieldsOfRoomList fieldsOfRoomList, Pageable pageable);
}
public interface RoomRepository extends JpaRepository<Room, Long>, RoomRepositoryCustom {
}
3). RoomRepositoryImpl 구현체 구현
@RequiredArgsConstructor
public class RoomRepositoryImpl implements RoomRepositoryCustom{
private final JPAQueryFactory queryFactory;
private final ParsingEntityUtils parsingEntityUtils;
@Override
public Page<RoomOfList> searchAll(FieldsOfRoomList fieldsOfRoomList, Pageable pageable) {
List<Room> result = queryFactory
.selectFrom(room)
.leftJoin(room.tags, tag1).fetchJoin()
.where(eqInterests(
fieldsOfRoomList.getExercise()),
eqArea(fieldsOfRoomList.getArea()),
participateCount(fieldsOfRoomList.getParticipantCount(), fieldsOfRoomList.isContainNoAdmittance()),
betweenTime(fieldsOfRoomList.getStartAppointmentDate(), fieldsOfRoomList.getEndAppointmentDate(), fieldsOfRoomList.isContainTimeClosing()),
eqTitle(fieldsOfRoomList.getRoomTitle()),
eqContent(fieldsOfRoomList.getRoomContent())
)
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.orderBy(sortRoomList(pageable))
.fetch();
return afterTreatment(result);
}
}
0. spring boot(gradle) 설정
buildscript {
ext {
queryDslVersion = "5.0.0"
}
}
plugins {
id 'org.springframework.boot' version '2.6.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"
id 'java'
}
dependencies {
implementation "com.querydsl:querydsl-jpa:${queryDslVersion}"
implementation "com.querydsl:querydsl-apt:${queryDslVersion}"
}
test {
useJUnitPlatform()
}
def querydslDir = "$buildDir/generated/querydsl"
querydsl {
jpa = true
querydslSourcesDir = querydslDir
}
sourceSets {
main.java.srcDir querydslDir
}
compileQuerydsl{
options.annotationProcessorPath = configurations.querydsl
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
querydsl.extendsFrom compileClasspath
}