본문 바로가기
개발/JPA

[JPA] Querydsl 조회 결과 DTO에 담는 법 / 예문

by Allonsy 2022. 1. 20.
반응형

1. Projections.bean(dto.class, field1, field2)

DTO setter 이용

List<UserDTO> dtos = query.select(
    Projections.bean(UserDTO.class, user.firstName, user.lastName)).fetch();

2. Projections.fields(dto.class, field1, field2)

DTO setter 대신 필드를 직접 사용하는 경우, setter 없어도 됨

List<UserDTO> dtos = query.select(
    Projections.fields(UserDTO.class, user.firstName, user.lastName)).fetch();

3. Projections.constructor(dto.class, field1, field2)

생성자 이용, 생성자 파라미터와 순서가 같아야함

List<UserDTO> dtos = query.select(
    Projections.constructor(UserDTO.class, user.firstName, user.lastName)).fetch();

4. @QueryProjection 어노테이션 with DTO 생성자

DTO 생성자에 @QueryProjection 어노테이션 달기

class CustomerDTO {
  @QueryProjection
  public CustomerDTO(long id, String name) {
     ...
  }
}

조회시 new 이용하여 생성자 사용

QCustomer customer = QCustomer.customer;
JPQLQuery query = new HibernateQuery(session);
List<CustomerDTO> dtos = query.select(new QCustomerDTO(customer.id, customer.name))
                              .from(customer).fetch();

5. @QueryProjection 어노테이션 with Entity 생성자

Entity 생성자에 @QueryProjection 어노테이션 달기

@Entity
class Customer {
  @QueryProjection
  public Customer(long id, String name) {
     ...
  }
}

QEntity.create(entity.field1, entity.field2)

QCustomer customer = QCustomer.customer;
JPQLQuery query = new HibernateQuery(session);
List<Customer> dtos = query.select(QCustomer.create(customer.id, customer.name))
                           .from(customer).fetch();

[참고 - Querydsl 레퍼런스 가이드]

http://querydsl.com/static/querydsl/5.0.0/reference/html_single/

 

Querydsl Reference Guide

The Java 6 APT annotation processing functionality is used in Querydsl for code generation in the JPA, JDO and Mongodb modules. This section describes various configuration options for the code generation and an alternative to APT usage. 3.3.1. Path initi

querydsl.com

 

반응형

댓글