Backend/Spring Boot
원본 글 보기

[JPA] QueryDSL 'No constructor found for class' 에러 해결

[JPA] QueryDSL 'No constructor found for class' 에러 해결

[에러]



com.querydsl.core.types.ExpressionException: No constructor found for class - with parameters:[]...

QueryDsl을 이용해서 Entity 에서 전체 필드를 호출하는 것이 아니라, 특정 필드들만 호출하거나, 연관된 다른 Entity의 필드를 동시에 호출하고 싶다면 아래와 같이 Projections.constructor를 사용한다.

[Repository]



jpaQueryFactory
                .select(Projections.constructor(MemberDTO.class,
                        member.email,
                        order.orderDate,
                        order.status
                        )
)
.from(member)
{...}

[DTO]



@Getter
@ToString
@AllArgsConstructor

public class MemberDTO {
private String memberEmail;
private LocalDateTime orderDate;
private OrderStatus orderStatus;
}
{...}

[원인]

Dto.class에서 정의하는 필드와 Repository에서 select로 표현하고자하는 필드가 완전히 일치하지 않아서 발생하는 문제이다.

[해결책]

1. 모든 필드의 타입이 일치해야 한다.

2. 모든 필드의 순서가 일치해야 한다.

3. Repo. 쪽에서의 필드명과 XxxDto 쪽에서의 필드명이 일치해야한다. 만약 다르다면, Repo. 쪽에서 .as("별칭") 메서드를 사용해서 Dto 쪽에서의 필드명과 같도록 별칭을 지정해주도록 한다.