Light Blue Pointer
본문 바로가기
Journal

QueryDSL 설정

by 개발바닥곰발바닥!!! 2024. 9. 5.

일단 gradle에 관련 설정들을 추가해준다

plugins {
    id 'com.ewerk.gradle.plugins.querydsl' version '1.0.10'
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.mysql:mysql-connector-j'

    implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta'
    annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta'
    annotationProcessor 'jakarta.persistence:jakarta.persistence-api'
    annotationProcessor 'jakarta.annotation:jakarta.annotation-api'
}

tasks.named('test') {
    useJUnitPlatform()
}

querydsl {
    jpa = true
}

compileQuerydsl{
    options.annotationProcessorPath = configurations.querydsl
}

configurations {
    querydsl.extendsFrom compileClasspath
}

 

 

JPAConfig를 Bean으로 등록해 준다

@Configuration
@EnableJpaAuditing
public class JPAConfig {
    @PersistenceContext
    private EntityManager entityManager;

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

 

compile / compileJava/ compileKotlin을 해줘야 QType 객체들이 생성되고 정상적으로 빌드할 수 있다

package com.lec.payroll.backend.payroll.repository;


import com.lec.payroll.backend.employee.model.Department;
import com.lec.payroll.backend.payroll.model.Payroll;

import java.util.List;

public interface PayrollDslRepository {

    public Integer getTotalPayrollsByDepartment(Department department);

    public List<Payroll> getAllPayrolls(int page, int size);
}
@RequiredArgsConstructor
@Repository
public class PayrollDslRepositoryImpl implements PayrollDslRepository{

    private final JPAQueryFactory jpaQueryFactory;

    @Override
    public Integer getTotalPayrollsByDepartment(Department department) {

        QPayroll payroll = QPayroll.payroll;
        QEmployee employee = QEmployee.employee;

        return jpaQueryFactory
                .select(payroll.paycheck.sum())
                .from(payroll)
                .join(payroll.employee, employee)
                .where(employee.department.eq(department))
                .fetchOne();
    }

    @Override
    public List<Payroll> getAllPayrolls(int page, int size) {
        QPayroll payroll = QPayroll.payroll;
        int offset = page*size;

        List<Payroll> payrolls = jpaQueryFactory
                .selectFrom(payroll)
                .offset(offset)
                .limit(size)
                .fetch();

        return payrolls;
    }
}

 

이런식으로 사용하면 된다