사내 한 도메인 서비스에 새로운 API 를 추가 개발해야 하는 업무가 있었다. 검색 api를 제공해야 하는 부분에서 queryDsl을 사용면서 좀 더 클린한 방식의 코드 작성을 고민해보았다.
*실제 코드가 아닌 컨셉 코드로 대체하였습니다.
@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
을 파라미터로 받아, 각각에 맞는 검색 쿼리를 생성하고 있다. 이러한 방식은 코드가 단순하고 직관적으로 보이지만, 앞으로의 확장성을 고려하면 문제가 될 수 있다.