• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

페이징, 정렬 다시 정리해서 질문드립니다.

24.01.04 03:24 작성 조회수 164

0

1.

이렇게 했을 때 페이지 처리와 정렬이 되었습니다. 여기서 정적으로 하려면 지금 작성한 것처럼 지정해주고 orderBy를 동적으로 처리하려면 동적쿼리 where절 처럼 메소드를 만들어서 MemberSearchCondition같은 곳에 정렬을 받아서 메소드로 만들고 orderBy에 넣어주면 되나요??

 

2.

Querydsl4RepositorySupport

@Repository
public abstract class Querydsl4RepositorySupport {
    private final Class domainClass;
    private Querydsl querydsl;
    private EntityManager entityManager;
    private JPAQueryFactory queryFactory;
    public Querydsl4RepositorySupport(Class<?> domainClass) {
        Assert.notNull(domainClass, "Domain class must not be null!");
        this.domainClass = domainClass;
    }
    @Autowired
    public void setEntityManager(EntityManager entityManager) {
        Assert.notNull(entityManager, "EntityManager must not be null!");
        JpaEntityInformation entityInformation =
                JpaEntityInformationSupport.getEntityInformation(domainClass, entityManager);
        SimpleEntityPathResolver resolver = SimpleEntityPathResolver.INSTANCE;
        EntityPath path = resolver.createPath(entityInformation.getJavaType());
        this.entityManager = entityManager;
        this.querydsl = new Querydsl(entityManager, new
                PathBuilder<>(path.getType(), path.getMetadata()));
        this.queryFactory = new JPAQueryFactory(entityManager);
    }
    @PostConstruct
    public void validate() {
        Assert.notNull(entityManager, "EntityManager must not be null!");
        Assert.notNull(querydsl, "Querydsl must not be null!");
        Assert.notNull(queryFactory, "QueryFactory must not be null!");
    }
    protected JPAQueryFactory getQueryFactory() {
        return queryFactory;
    }
    protected Querydsl getQuerydsl() {
        return querydsl;
    }
    protected EntityManager getEntityManager() {
        return entityManager;
    }
    protected <T> JPAQuery<T> select(Expression<T> expr) {
        return getQueryFactory().select(expr);
    }
    protected <T> JPAQuery<T> selectFrom(EntityPath<T> from) {
        return getQueryFactory().selectFrom(from);
    }
    protected <T> Page<T> applyPagination(Pageable pageable,
                                          Function<JPAQueryFactory, JPAQuery> contentQuery) {
        JPAQuery jpaQuery = contentQuery.apply(getQueryFactory());
        List<T> content = getQuerydsl().applyPagination(pageable,
                jpaQuery).fetch();
        return PageableExecutionUtils.getPage(content, pageable,
                jpaQuery::fetchCount);
    }
    protected <T> Page<T> applyPagination(Pageable pageable,
                                          Function<JPAQueryFactory, JPAQuery> contentQuery, Function<JPAQueryFactory,
            JPAQuery> countQuery) {
        JPAQuery jpaContentQuery = contentQuery.apply(getQueryFactory());
        List<T> content = getQuerydsl().applyPagination(pageable,
                jpaContentQuery).fetch();
        JPAQuery countResult = countQuery.apply(getQueryFactory());
        return PageableExecutionUtils.getPage(content, pageable,
                countResult::fetchCount);
    }

}

 여기서 보면 fetchCount를 사용하고 있는데 deprecated가 뜹니다. 이거를 어떻게 수정해줘야 할까요?

 

  1. Querydsl4RepositorySupport을 사용해서

    public Page<Member> applyPagination(MemberSearchCondition condition, Pageable pageable) {
        return applyPagination(pageable, query ->
                query.selectFrom(member)
                        .leftJoin(member.team, team)
                        .where(userNameEq(condition.getUserName()),
                                teamNameEq(condition.getTeamName()),
                                ageGoe(condition.getAgeGoe()),
                                ageLoe(condition.getAgeLoe())
                        )
        );
    }

    public Page<Member> applyPagination2(MemberSearchCondition condition, Pageable pageable) {
        return applyPagination(pageable, contentQuery ->
                contentQuery.selectFrom(member)
                        .leftJoin(member.team, team)
                        .where(userNameEq(condition.getUserName()),
                                teamNameEq(condition.getTeamName()),
                                ageGoe(condition.getAgeGoe()),
                                ageLoe(condition.getAgeLoe())
                        ), countQuery -> countQuery
                .select(member.id)
                .from(member)
                .where(userNameEq(condition.getUserName()),
                        teamNameEq(condition.getTeamName()),
                        ageGoe(condition.getAgeGoe()),
                        ageLoe(condition.getAgeLoe()))
        );
    }

이렇게 구현한 거에도 1번과 같이 메소드로 orderBy에 넣으면 되는건가요?

 

  1. 1번과 3번의 차이는 코드를 더 가독성있게 하려고 하는건가요 아니면 성능상의 차이점이라던지 더 큰 장점이 있나요?

답변 2

·

답변을 작성해보세요.

1

David님의 프로필

David

2024.01.05

안녕하세요. 유요한님, 공식 서포터즈 David입니다.

  1. 네, 맞습니다.

  2. https://www.inflearn.com/questions/379310 글 답변을 참고해 주세요.

  3. 네, 맞습니다.

  4. 가독성을 향상 시키기 위함입니다.

감사합니다🙂

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2024.01.04

안녕하세요, 인프런 AI 인턴입니다.

질문하신 내용과 유사한 주제로 강사님이 답변해주신 게시글을 찾았습니다. 해당 답변은 Querydsl에서 Sort 기능을 구현하는 방법과 관련된 내용입니다. 강사님의 답변은 Sort를 Pageable에 포함시켜 해당 조건을 함께 적용하는 방법에 대해 설명하고 있습니다. 이는 정렬을 동적으로 처리할 때 참고하실 수 있을 것 같습니다.

또한, fetchCount가 deprecated된 문제에 대해서는 fetchOne으로 대체하여 사용하는 방법을 제시하고 있습니다.

아래 링크에서 자세한 내용을 확인하실 수 있습니다.

추가로, 정렬 로직을 동적으로 적용하기 위해서는 Querydsl에서 제공하는 OrderSpecifier 등을 이용하여 구현할 수 있으며, 메소드를 만들어서 동적인 쿼리를 생성하는 방식이 맞습니다.

성능상의 차이보다는 코드 가독성이나 유지 보수의 용이성을 위해 메소드 분리를 고려하는 것이 일반적인 목적입니다.

감사합니다.