JPA & SQL

[JPA&SQL] QueryDSL - 적용하기

김먼저 2022. 8. 10. 10:52
build.gradle

 

/*
 * queryDSL 설정 추가
 */
// querydsl에서 사용할 경로 설정
def querydslDir = "$buildDir/generated/querydsl"
// JPA 사용 여부와 사용할 경로를 설정
querydsl {
    jpa = true
    querydslSourcesDir = querydslDir
}
// build 시 사용할 sourceSet 추가
sourceSets {
    main.java.srcDir querydslDir
}
// querydsl 컴파일시 사용할 옵션 설정
compileQuerydsl{
    options.annotationProcessorPath = configurations.querydsl
}
// querydsl 이 compileClassPath 를 상속하도록 설정
configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
    querydsl.extendsFrom compileClasspath
}
plugin INFO
id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"
implementation "com.querydsl:querydsl-jpa:4.4.0"
implementation "com.querydsl:querydsl-apt:4.4.0"
implementation group: 'ch.simas.qlrm', name: 'qlrm', version: '1.7.1'

 

 

 

 

 

config

@Configuration
public class QuerydslConfiguration {

    @PersistenceContext
    private EntityManager entityManager;

    @Bean
    public JPAQueryFactory jpaQueryFactory() {
        return new JPAQueryFactory(entityManager);
    }
}

 

 

 

QueryDSL

 

 public Page<RoomInfo> findByStatus(String status, Pageable paging){
        List<RoomInfo> roomInfos = queryFactory
                .select(Projections.constructor(RoomInfo.class,
                        roomMasterEntity.roomId,
                        roomMasterEntity.roomName,
                        roomMasterEntity.roomPrivateYn,
                        roomMasterEntity.roomPassword,
                        memberMasterEntity.memId,
                        memberMasterEntity.profileImgUrl,
                        memberMasterEntity.nickName))
                .from(roomMasterEntity)
                .innerJoin(memberMasterEntity)
                .on(roomMasterEntity.creator.eq(memberMasterEntity.memId))
                .where(roomMasterEntity.status.eq(status))
                .offset(paging.getOffset())
                .limit(paging.getPageSize())
                .fetch();

        Long count = queryFactory
                .select(roomMasterEntity.count())
                .from(roomMasterEntity)
                .innerJoin(memberMasterEntity)
                .on(roomMasterEntity.creator.eq(memberMasterEntity.memId))
                .where(roomMasterEntity.status.eq(status))
                .fetchOne();

        return new PageImpl<>(roomInfos, paging, count);

 

 

 

Entity 변경 시 반드시 compileQuerydsl 실행하여 갱신하기

Gradle에서 compileQuerydsl을 더블 클릭하여 실행하기.

 

실행 결과