본문 바로가기

JPA

Query DSL 설정

1. build.gradle

build.gradle 에 query dsl 설정 추가

buildscript {
    /** ext : 전역변수 설정 */
    ext {
        springBootVersion = '2.2.6.RELEASE'
        querydslPluginVersion = '1.0.10'
    }
    repositories {
        jcenter()
        maven { url "https://plugins.gradle.org/m2/" } // plugin 저장소
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("io.spring.gradle:dependency-management-plugin:1.0.9.RELEASE")
        classpath("gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:${querydslPluginVersion}")
    }
}
/** query dsl */
dependencies {
    implementation 'com.querydsl:querydsl-jpa'
}

def generatedSourcesDir = "src/main/generated/querydsl"

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

sourceSets {
    main.java.srcDirs += generatedSourcesDir
}

compileQuerydsl {
    options.annotationProcessorPath = configurations.querydsl
}

configurations {
    querydsl.extendsFrom compileClasspath
}

 

2. QuerydslConfig 파일 생성

package com.-;

import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;

@Configuration
@RequiredArgsConstructor
public class QuerydslConfig {

    private final EntityManager em;

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

 

! 만약 여러 스키마를 사용중이어서 datasourceConfig가 여러개인 경우, 모든 스키마 설정을 해줘야 한다.

 - datasourceConfig의 LocalContainerEntityManagerFactoryBean 의 @Bean name을 @Qualifier로 선언해준다.

package com.-;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.persistence.EntityManager;

@Configuration
public class QuerydslConfig {

    private final EntityManager entityManager1;
    private final EntityManager entityManager2;

    public QuerydslConfig(@Qualifier("entityManagerFactory1") EntityManager entityManager1,
                          @Qualifier("entityManagerFactory2") EntityManager entityManager2) {
        this.entityManager1 = entityManager1;
        this.entityManager2 = entityManager2;
    }

    @Bean
    public JPAQueryFactory jpaQueryFactory1(){
        return new JPAQueryFactory(entityManager1.getEntityManagerFactory().createEntityManager());
    }

    @Bean
    @Primary
    public JPAQueryFactory jpaQueryFactory2(){
        return new JPAQueryFactory(entityManager2.getEntityManagerFactory().createEntityManager());
    }
}

 

3. Repository 설정

1) customRepository 생성

package com.-.dao;


import com.-vo.Project;

import java.util.List;

public interface ProjectCustomRepository{

    List<Project> findByear(int year);
}

 

2) customRepository 구현한 repositoryImpl 생성

package com.-.dao;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.-.Project;
import lombok.RequiredArgsConstructor;

import static com.-.vo.QProject.project;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class ProjectRepositoryImpl implements ProjectCustomRepository {
    private final JPAQueryFactory queryFactory;

    @Override
    public List<Project> findByYear(int year){
        return queryFactory.selectFrom(project)
                .where(project.year.eq(year))
                .fetch();
    }
}

 

! project가 로드되지 않는경우

 - Gradle > Tasks > other > compileQuerydsl 을 실행해준다.

 

3) JpaRepository 와 CustomRepository 상속 받은 repository 생성

package com.-.dao;

import com.-.ProjectPK;
import com.-.Project;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProjectRepository extends JpaRepository<Project, ProjectPK>, ProjectCustomRepository {

}

 

4. Repository 사용

1) repository 사용

 - service 단에서 repository사용 시 ProjectRepository에서 JpaRepository와 ProjectCustomRepository를 상속받고 있기 때문에 ProjectRepository로만 접근하여 사용한다.

package com.-.service;

import com.-.ProjectRepository;
import com.-.ProjectDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    public List<ProjectDTO> findByYear(int year){
        return projectRepository.findByYear(year);
    }
}

 

 

2) Entity 를 직접 사용하는 것보다 DTO를 사용하는 것이 좋다.

 - DTO 예시

package com.-.vo;

import lombok.Getter;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Getter
@NoArgsConstructor
public class ProjectDTO {
    private String id;
    private String name;
    private BigDecimal rate;

    public ProjectDTO(String id, String name, BigDecimal rate){
        this.id = id;
        this.name = name;
        this.rate = rate;
    }

    public TimesheetRateDTO(String id, int index, String name, BigDecimal rate){
        this.id = id;
        this.name = name + index;
        this.rate = rate;
    }
}

 


 

!QuerydslConfig 설정 시 꼭 확인하기

https://hit-sand.tistory.com/entry/Querydsl-Connection-is-closed?category=1066855

'JPA' 카테고리의 다른 글

spring boot jpa 설정  (0) 2024.03.25
[Querydsl] Connection is closed  (0) 2023.07.25
Querydsl Projection 패턴  (0) 2023.05.30