3. JPA - QueryDSL, @PersistenceContext

지원·2026년 3월 11일

SpringBoot

목록 보기
13/17
post-thumbnail

QueryDSL

  • SQL이나 JPQL을 문자열로 쓰지 않고,
    자바 문법처럼 안전하게 조회 조건을 만드는 기술
    -동적 쿼리를 만들기 좋다.

  • 사용법

  1. build.gradle 추가
dependencies {
    implementation 'com.querydsl:querydsl-jpa::jakarta'
    annotationProcessor 'com.querydsl:querydsl-apt::jakarta'
    annotationProcessor 'jakarta.annotation:jakarta.annotation-api'
    annotationProcessor 'jakarta.persistence:jakarta.persistence-api'
}
  1. application.yml 추가
spring:
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        highlight_sql: true
        use_sql_comments: true
  1. Entity 객체 추가
  2. DSL 빌드 처리

build 실행, main 실행 중 바꿔서 설정할 수도 있음

  • 빌드 처리시 QProdeuct 클래스 생성됨
    프로젝트 폴더 > build > generated > source > annotationProcessor > java > main > 프로젝트 네임 > QProduct
    *QueryDSL이 만든 조회 전용 도우미
  • Antity 필드가 수정되었을 경우, 빌드처리를 새로 해서 QProduct가 재생성 되도록 만들어야함
  1. JPAQueryFactory 스프링 빈 생성
    JPAQueryFactory 클래스를 스프링 빈으로 등록
@Configuration
public class QueryDslConfig{
	@PersistenceContext
    private EntityManager entityManager;
    
    @Bean
    public JPAQueryFactory jpaQueryFactory(){
    return new JPAQueryFactory(entityManager);
    }
}

EntityManager를 주입받고, 그걸 기반으로 JPAQueryFactory를 만든다.
나중에 레포지터리에서 주입받아 사용

  1. 커스텀 레포지토리 작성
    보통 JpaRepository 안에 바로 넣기보다 커스텀 레포지토리로 분리해서 사용한다.
  • 인터페이스
package org.example.orgmanager.repository;

import org.example.orgmanager.domain.Employee;
import java.util.List;

public interface EmployeeRepositoryCustom {
    List<Employee> searchByName(String name);
}
  • 구현체
@RequiredArgsConstructor
public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom {

    private final JPAQueryFactory queryFactory;

    @Override
    public List<Employee> searchByName(String name) {
        QEmployee employee = QEmployee.employee;

        return queryFactory
                .selectFrom(employee)
                .where(employee.name.eq(name))
                .fetch();
    }
}

QEmplyee를 사용해서 Employee 테이블에서 이름이 같은 데이터를 조회한 후, fetch()로 결과 리스트 반환

  1. 기존 Repository와 합치기
public interface EmployeeRepository
        extends JpaRepository<Employee, Long>, EmployeeRepositoryCustom {
}
  • 조건 메서드
    eq() : 같다
    ne() : 같지 않다
    goe() : 크거나 같다
    gt() : 크다
    loe() : 작거나 같다
    lt() : 작다
    contatins() : 포함
    startsWith() : ~로 시작
    endsWith() : ~로 끝남

@PersistenceContext

  • JPA의 EntityManager를 주입할 때 사용
  • 정확히는 영속성 컨텍스트와 연결된 EntityManager를 넣어줌
@PersistenceContext
private EntityManager entityManager;
  • @Autowired과의 차이
    @Autowired는 스프링 빈을 주입할 때 사용
profile
개발 공부하는 김지원

0개의 댓글