0. 목차

  1. 목차
  2. 개요
  3. 첫 번째 구현 및 문제점
  4. 두 번째 구현 및 문제점
  5. 세 번째 구현 및 문제점
  6. 네 번째 구현 및 문제점
  7. 결론

1. 개요

사내 한 도메인 서비스에 새로운 API 를 추가 개발해야 하는 업무가 있었다. 검색 api를 제공해야 하는 부분에서 queryDsl을 사용면서 좀 더 클린한 방식의 코드 작성을 고민해보았다.

*실제 코드가 아닌 컨셉 코드로 대체하였습니다.

2. 첫 번째 구현 및 문제점

구현

 @RequiredArgsConstructor
@Component
public class DomainRepositoryImpl implements DomainCustomRepository {

    private final JPAQueryFactory queryFactory;

    @Override
    public Page<DomainEntity> retrieve(String searchKeyword, String searchType, Pageable pageable) {
        QDomainEntity qDomainEntity = QDomainEntity.domainEntity;
        BooleanExpression expression = searchKeyword(searchType, searchKeyword);

        List<DomainEntity> results = queryFactory
                .selectFrom(qDomainEntity)
                .where(expression)
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetch();

        long total = queryFactory
                .selectFrom(qDomainEntity)
                .where(expression)
                .fetchCount();

        return PageableExecutionUtils.getPage(results, pageable, () -> total);
    }

    private BooleanExpression searchKeyword(String searchType, String searchKeyword) {
        if (searchKeyword == null || searchKeyword.isEmpty()) {
            return null;
        }

        QDomainEntity qDomainEntity = QDomainEntity.domainEntity;

        if ("id".equalsIgnoreCase(searchType)) {
            return qDomainEntity.domainId.eq(Long.valueOf(searchKeyword));
        } else {
            return qDomainEntity.domainName.containsIgnoreCase(searchKeyword);
        }
    }
}

위의 자바 코드는 Querydsl를 활용한 DomainRepositoryImpl 클래스에 대한 구현다. 여기서는 searchKeyword와 searchType을 파라미터로 받아, 각각에 맞는 검색 쿼리를 생성하고 있다. 이러한 방식은 코드가 단순하고 직관적으로 보이지만, 앞으로의 확장성을 고려하면 문제가 될 수 있다.

문제점

  1. 유연성 부족: 현재 구현은 'id'와 '이름'에 대한 검색만 가능합니다. 만약에 다른 검색 조건이 추가된다면, 메소드 수정이 불가피하다.
  2. 코드 수정 필요성: 새로운 요구사항이 생길 때마다 서버 코드를 변경해야 하기 때문에 유지 보수가 어렵다.

3. 두 번째 구현 및 문제점

구현