๐Ÿ“˜ Web/Spring, JPA

[QueryDSL] @QueryProjection (SELECT์ ˆ ๋Œ€์ƒ ์ง€์ •)

a n u e 2023. 8. 25. 10:45

 

ํ”„๋กœ์ ์…˜ (Projections)

QueryDSL์„ ์ด์šฉํ•ด Entity ์ „์ฒด๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ์กฐํšŒ ๋Œ€์ƒ์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

ํŠน์ • ์ปฌ๋Ÿผ๋งŒ์„ SELECT ํ•ด์˜ค๋Š” ์ปค์Šคํ…€ ๋ฉ”์„œ๋“œ๋ฅผ ์ƒ์„ฑํ•œ ๊ฒฝ์šฐ,

Entity์—์„œ ์ „์ฒด ํ•„๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ํŠน์ • ๋Œ€์ƒ๋งŒ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ๊ธฐ ๋•Œ๋ฌธ์—

(๋‚˜๊ฐ™์€ ๊ฒฝ์šฐ) ์ƒ์„ฑ์ž ๋ฐฉ์‹์ธ Projectsions.constructor์„ ์ด์šฉํ•˜์—ฌ DTO์— ์ •์˜ํ•œ ํ•„๋“œ๋งŒ์„ ํ˜ธ์ถœํ•˜์˜€๋‹ค.

๊ทธ๋Ÿฐ๋ฐ DTO ์ค‘์—์„œ๋„ ํŠน์ • ํ•„๋“œ๋งŒ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ๋‹ค๋ฉด?

 

 

@RequiredArgsConstructor
public class TestRepoImpl implements TestRepoCustom  {
    private final JPAQueryFactory jpaQueryFactory;
    @Override
    public List<TestDTO> find() {
        QTestEntity hc3 = QTestEntity.testEntity;

        return jpaQueryFactory
                .select(Projections.constructor(TestDTO.class,
                        hc3.field1))
                .from(hc3)
                .groupBy(hc3.field1)
                .orderBy(OrderByNull.DEFAULT)
                .fetch();
    }
}

 

@Getter
@Setter
@ToString
@AllArgsConstructor
public class TestDTO {
    private String field1;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<TestSubDTO> subList = new ArrayList<>();
}

 

 

TestDTO์—์„œ field1๋งŒ ํ˜ธ์ถœํ•˜๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ, ์ž๊พธ ์—๋Ÿฌ๊ฐ€ ๋–จ์–ด์ง„๋‹ค.

 

no constructor found for class com.xxx.demo.model.testDTOwith parameters: ... 

 

์ฃผ๋กœ DTO์—์„œ ์ •์˜ํ•˜๋Š” ํ•„๋“œ์™€ Repo์—์„œ ํ‘œํ˜„ํ•˜๊ณ ์ž ํ•˜๋Š” ํ•„๋“œ๊ฐ€ ๋ถˆ์ผ์น˜ํ•˜์—ฌ ๋ฐœ์ƒํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

๋ชจ๋“  ํ•„๋“œ์˜ ํƒ€์ž…/์ˆœ์„œ๊ฐ€ ์ผ์น˜ํ•ด์•ผํ•˜๋ฉฐ, ํ•„๋“œ๋ช…๋„ ์ผ์น˜ํ•ด์•ผํ•œ๋‹ค. ๋‹ค๋ฅด๋‹ค๋ฉด .as์„ ์‚ฌ์šฉํ•ด ๋ณ„์นญ์„ ์ง€์ •ํ•˜์—ฌ์„œ ๋งž์ถฐ์ฃผ์–ด์•ผํ•œ๋‹ค.

๋‚˜๊ฐ™์€ ๊ฒฝ์šฐ์—๋Š” ์•„๋ฌด๋ž˜๋„ TestSubDTO ๊ฐ์ฒด๋ฅผ ๋‹ด์„ subList ๋•Œ๋ฌธ์ธ ๊ฒƒ ๊ฐ™์•˜๋‹ค.

 

field1๋งŒ ๊ฐ€์ ธ์˜ค๋ฉด ๋˜๋Š”๋ฐ .... subList๋Š” ๋‹ค๋ฅธ ๊ณณ์—์„œ ์‚ฌ์šฉํ•ด์„œ ์ œ๊ฑฐํ•  ์ˆ˜๋„ ์—†๊ณ  ... 

DTO ์ค‘์—์„œ๋„ ํŠน์ • ํ•„๋“œ๋งŒ์„ ๊ฐ€์ ธ์˜ค๋„๋ก ์ง€์ •ํ•  ์ˆ˜ ์—†์„๊นŒ ์ฐพ์•„๋ณด๋‹ˆ 

DTO ์ƒ์„ฑ์ž์™€ @QuertProjection ์–ด๋…ธํ…Œ์ด์…˜์„ ํ™œ์šฉํ•˜๋ฉด ๋œ๋‹ค๊ณ  ํ•œ๋‹ค.

 

@Getter
@Setter
@ToString
@AllArgsConstructor
public class TestDTO {
    private String field1;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<TestSubDTO> subList = new ArrayList<>();
    
    @QueryProjection
    public TestDTO(String field1) {
        this.field1 = field1;
    }
}

 

field1๋งŒ์„ ์ž˜ ๊ฐ€์ ธ์˜จ๋‹ค. ํ•ด๊ฒฐ!