Querydsl - 4.0.0이상 버전에서 DTO사용하기.

4.0.0이전 버전

최근 회사에서 프로젝트를 하면서 queryDSL를 사용할 기회가 있었다.
프로젝트를 하던 도중 Domain이 아닌 DTO를 사용해야 할 경우가 있었는데, 4.0.0 버전까지는 JPQL사용 시 .fetch() 다음 .list()를 하면 되었다.

// Query and project into DTO:

query = new JPASQLQuery(entityManager, templates);
List<CatDTO> catDTOs = query.from(cat)
    .orderBy(cat.name.asc())
    .list(Projections.constructor(CatDTO.class, cat.id, cat.name));

4.0.0이후 버전

하지만 4.0.0이후 버전에서는 .list()가 없어지고, 다른 방법이 생겼다.
공식 레퍼런스 문서를 확인하면

// Query and project into DTO:

query = new JPASQLQuery<Void>(entityManager, templates);
List<CatDTO> catDTOs = query.select(Projections.constructor(CatDTO.class, cat.id)
    .from(cat)
    .orderBy(cat.name.asc())
    .fetch();

이렇게 바뀌었다.

공통적으로 DTO.class에 생성자가 있어야한다. 또 객체를 파라미터로 넘겨서 생성자에서 한가지 작업을 해줘야한다.

public DTO(Cat cat) {
  this.setCatId(cat.getCatId());
  }

잊어버릴까봐 기록한다!