오봉이와 함께하는 개발 블로그
Querydsl - 동적 쿼리와 성능 최적화 조회 Where절 파라미터 사용 본문
728x90
동적 쿼리와 성능 최적화 조회 - Where절 파라미터 사용
Where절에 파라미터를 사용한 예제
public List<MemberTeamDto> search(MemberSearchCondition condition) {
return queryFactory
.select(new QMemberTeamDto(
member.id,
member.username,
member.age,
team.id,
team.name
))
.from(member)
.leftJoin(member.team, team)
.where(
usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe()))
.fetch();
}
private BooleanExpression usernameEq(String username) {
return isEmpty(username) ? null : member.username.eq(username);
}
private BooleanExpression teamNameEq(String teamName) {
return isEmpty(teamName) ? null : member.team.name.eq(teamName);
}
private BooleanExpression ageGoe(Integer ageGoe) {
return ageGoe == null ? null : member.age.goe(ageGoe);
}
private BooleanExpression ageLoe(Integer ageLoe) {
return ageLoe == null ? null : member.age.loe(ageLoe);
}
참고 : where 절에 파라미터 방식을 사용하면 조건 재사용 가능
public List<Member> findMember(MemberSearchCondition condition) {
return queryFactory
.selectFrom(member)
.leftJoin(member.team, team)
.where(usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe()))
.fetch();
}
테스트
@Test
void search() {
Team teamA = new Team("teamA");
Team teamB = new Team("teamB");
em.persist(teamA);
em.persist(teamB);
Member member1 = new Member("member1", 10, teamA);
Member member2 = new Member("member2", 20, teamA);
Member member3 = new Member("member3", 30, teamB);
Member member4 = new Member("member4", 40, teamB);
em.persist(member1);
em.persist(member2);
em.persist(member3);
em.persist(member4);
MemberSearchCondition condition = new MemberSearchCondition();
condition.setAgeGoe(35);
condition.setAgeLoe(40);
condition.setTeamName("teamB");
List<MemberTeamDto> result = memberJapRepository.search(condition);
assertThat(result).extracting("username").containsExactly("member4");
}
인프런 김영한 지식공유자님 강의 : 실전! Querydsl
728x90
'BE > JPA' 카테고리의 다른 글
Querydsl - 스프링 데이터 JPA 리포지토리로 변경 (1) | 2022.09.20 |
---|---|
Querydsl - 조회 API 컨트롤러 개발 (0) | 2022.09.20 |
Querydsl - 동적 쿼리와 성능 최적화 조회 Builder 사용 (0) | 2022.09.20 |
Querydsl - 순수 JPA와 Querydsl (0) | 2022.09.20 |
Querydsl - SQL Function 호출하기 (0) | 2022.09.19 |
Comments