Here is some example code:
package com.fallen.angel.test.repository;
import java.util.List;
import com.fallen.angel.demo.entity.QBoard;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.SimpleExpression;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.querydsl.jpa.sql.JPASQLQuery;
import com.querydsl.sql.SQLTemplates;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
public class BoardTestRepositoryCustomImpl implements BoardTestRepositoryCustom {
@PersistenceContext
private EntityManager em;
private final JPAQueryFactory queryFactory;
private final QBoard qBoard = QBoard.board;
public BoardTestRepositoryCustomImpl(JPAQueryFactory queryFactory) {
this.queryFactory = queryFactory;
}
//...
@Override
public List<String> boardTest() {
JPASQLQuery<?> q = new JPASQLQuery<>(em, SQLTemplates.DEFAULT);
SimpleExpression<String> writer = Expressions.as(
JPAExpressions.select(qBoard.writer)
.from(qBoard)
, "board");
List<String> result = q
.select(
Projections.constructor(String.class, qBoard.writer)
).distinct()
.from(
writer
)
.fetch();
return result;
}
}
And there is the built SQL query:
Hibernate:
select
distinct board.writer
from
(select
board.writer
from
board board) as board