-
05. Querydsl SubqueryBackEnd/Querydsl 2021. 7. 25. 17:38반응형
> com.querydsl.jpa.JPAExpressions 사용
> querydsl은 FROM절 서브쿼리를 지원하지 않는다. (SELECT, WHERE절만 가능)
1. WHERE절 서브쿼리
@Test
public void subQuery() throws Exception {
QMember memberSub = new QMember("memberSub");
List<Member> result = queryFactory
.selectFrom(member)
/** 1) 나이가 가장 많은 회원 조회
.where(member.age.eq( JPAExpressions
.select(memberSub.age.max())
.from(memberSub)
))
*/
/** 2) 나이가 평균 나이 이상인 회원
.where(member.age.goe(JPAExpressions
.select(memberSub.age.avg())
.from(memberSub)
))
*/
// 3) in
.where(member.age.in(JPAExpressions
.select(memberSub.age)
.from(memberSub)
.where(memberSub.age.gt(10))
))
.fetch();// 2. SELECT절 서브쿼리 (Scala Subquery)
List<Tuple> fetch = queryFactory
.select(member.username,
JPAExpressions
.select(memberSub.age.avg())
.from(memberSub)
).from(member)
.fetch();
for (Tuple tuple : fetch) {
System.out.println("username = " + tuple.get(member.username));
System.out.println("age = " + tuple.get(JPAExpressions.select(memberSub.age.avg()).from(memberSub)));
}
/** static import 활용
import static com.querydsl.jpa.JPAExpressions.select;
List<Member> result = queryFactory
.selectFrom(member)
.where(member.age.eq(
select(memberSub.age.max())
.from(memberSub)
))
.fetch();
*/
}반응형'BackEnd > Querydsl' 카테고리의 다른 글
07. Querydsl 상수, 문자 더하기 (0) 2021.07.27 06. Querydsl Case (0) 2021.07.27 04. Querydsl Join (0) 2021.07.18 03. Querydsl 기본 문법 (0) 2021.07.17 01. Querydsl 레퍼런스 문서 (0) 2021.07.11