[Querydsl] 조회 동적 쿼리 Builder, where

Welcome to Seoyun Dev Log·2023년 4월 29일
0

JPA

목록 보기
11/15

1. 동적 쿼리와 성능 최적화

StringUtils.hasText()

  • 파라미터로 문자열을 받을 때 null, "", empty가 아닐 때 true
 if (StringUtils.hasText(memberSearchCondition.getUsername())) {
            builder.and(member.username.eq(memberSearchCondition.getUsername()));
        }

1) Builder

  • MemberJpaRepository
public List<MemberTeamDto> searchByBuilder(MemberSearchCondition memberSearchCondition) {
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.hasText(memberSearchCondition.getUsername())) {
            builder.and(member.username.eq(memberSearchCondition.getUsername()));
        }

        if (StringUtils.hasText(memberSearchCondition.getTeamName())) {
            builder.and(team.name.eq(memberSearchCondition.getTeamName()));
        }

        if (memberSearchCondition.getAgeGoe() != null) {
            builder.and(member.age.goe(memberSearchCondition.getAgeGoe()));
        }

        if (memberSearchCondition.getAgeLoe() != null) {
            builder.and(member.age.goe(memberSearchCondition.getAgeLoe()));
        }

        return jpaQueryFactory
                .select(new QMemberTeamDto(
                        member.id.as("memberId"),
                        member.username,
                        member.age,
                        team.id.as("teamId"),
                        team.name.as("teamName"))
                )
                .from(member)
                .leftJoin(member.team, team)
                .where(builder)
                .fetch();
    }
  • MemberTeamDto
import com.querydsl.core.annotations.QueryProjection;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class MemberTeamDto {
    private Long memberId;
    private String username;
    private int age;
    private Long teamId;
    private String teamName;

    @QueryProjection
    public MemberTeamDto(Long memberId, String username, int age, Long teamId, String teamName) {
        this.memberId = memberId;
        this.username = username;
        this.age = age;
        this.teamId = teamId;
        this.teamName = teamName;
    }
}
  • Test
@DisplayName("searchTest")
    @Test
    void searchTest() {
        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 = MemberSearchCondition.builder()
                .ageGoe(35)
                .ageLoe(40)
                .teamName("teamB")
                .build();

        List<MemberTeamDto> result = memberJpaRepository.searchByBuilder(condition);
        assertThat(result).extracting("username")
                .containsExactly("member4");
    }

📌만약
MemberSearchCondition condition = new MemberSearchCondition();
으로 데이터가 없는 상태로 보내게 될 경우 모든 데이터를 다 조회한다
운영하다보면 데이터가 쌓이는데 이 모든걸 가지고오게 된다면 성능최적화에 문제가 발생할 수 있음. 데이터를 확인하거나 기본 파라미터가 존재하도록 짜기


2) where절 파라미터

	public List<MemberTeamDto> searchByWhere(MemberSearchCondition condition) {
        return jpaQueryFactory
                .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 usernameCond) {
        return StringUtils.hasText(usernameCond) ? member.username.eq(usernameCond) : null;
    }

    private BooleanExpression teamNameEq(String teamNameCond) {
        return StringUtils.hasText(teamNameCond) ? team.name.eq(teamNameCond) : null;
    }

    private BooleanExpression ageGoe(Integer ageGoeCond) {
        return ageGoeCond != null ? member.age.goe(ageGoeCond) : null;
    }

    private BooleanExpression ageLoe(Integer ageLoeCond) {
        return ageLoeCond != null ? member.age.loe(ageLoeCond) : null;
    }

: where 절의 장점인 조립하여 사용하는 위 방법을 변경한 아래와 같다

	public List<Member> searchMember(MemberSearchCondition condition) {
        //select만 바꿔서 메서드 코드를 재사용 할 수 있다.
        return jpaQueryFactory
                .selectFrom(member)
                .leftJoin(member.team, team)
                .where(usernameEq(condition.getUsername())
                        , teamNameEq(condition.getTeamName())
                        , ageBetween(condition.getAgeLoe(), condition.getAgeGoe())
                )
                .fetch();
    }
    
    private BooleanExpression ageBetween(int ageLoe, int ageGoe) {
        return ageGoe(ageLoe).and(ageGoe(ageGoe));
    }

    private BooleanExpression usernameEq(String usernameCond) {
        return StringUtils.hasText(usernameCond) ? member.username.eq(usernameCond) : null;
    }

    private BooleanExpression teamNameEq(String teamNameCond) {
        return StringUtils.hasText(teamNameCond) ? team.name.eq(teamNameCond) : null;
    }

    private BooleanExpression ageGoe(Integer ageGoeCond) {
        return ageGoeCond != null ? member.age.goe(ageGoeCond) : null;
    }

    private BooleanExpression ageLoe(Integer ageLoeCond) {
        return ageLoeCond != null ? member.age.loe(ageLoeCond) : null;
    }
    

init

: local로 실행시 InitMember를 bean으로 관리하고
InitMemberService를 bean으로 생성해서 @PostConstruct 어노테이션이 해당 메서드 init()을 초기화하는 것이 보장되어되도록 해주는 것

package study.querydslpractice.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import study.querydslpractice.entity.Member;
import study.querydslpractice.entity.Team;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Profile("local")
@Component
@RequiredArgsConstructor
public class InitMember {

    private final InitMemberService initMemberService;

    @PostConstruct
    public void init(){
        initMemberService.init();
    }

    @Component
    static class InitMemberService{
        @PersistenceContext
        private EntityManager em;

        @Transactional
        public void init() {
            Team teamA = new Team("teamA");
            Team teamB = new Team("teamB");
            em.persist(teamA);
            em.persist(teamB);

            for (int i = 0; i < 100; i++) {
                Team selectedTeam = i % 2 == 0 ? teamA : teamB;
                em.persist(new Member("member" + i, i, selectedTeam));
            }
        }
    }
}
  • API
    : MemberSearchCondition DTO가 null인 경우
    제외될 수 있도록 searchByWhere querydsl로 처리
    따라서 MemberSearchCondition안에 들어가있는것을 다 넣어서 하나의 메서드로 where문을 처리할 수 있다
package study.querydslpractice.controller;


import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import study.querydslpractice.dto.MemberSearchCondition;
import study.querydslpractice.dto.MemberTeamDto;
import study.querydslpractice.repository.MemberJpaRepository;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class MemberController {
    private final MemberJpaRepository memberJpaRepository;

    @GetMapping("/v1/members")
    public List<MemberTeamDto> searchMemberV1(MemberSearchCondition condition) {
        return memberJpaRepository.searchByWhere(condition);
    }
}
profile
하루 일지 보단 행동 고찰 과정에 대한 개발 블로그

0개의 댓글