带有Spring Pageable的JPAQuery

时间:2018-07-14 12:31:43

标签: java spring spring-boot spring-data-jpa querydsl

我想将org.springframework.data.domain.Pageablecom.querydsl.jpa.impl.JPAQuery一起使用,或者是否有可靠的解决方法来使Pageable与JPAQuery一起使用?

1 个答案:

答案 0 :(得分:0)

所以我found很高兴为什么要让他们一起发表完整的例子:

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.persistence.EntityManager;

public class Example {
    public void example(Pageable pageable, EntityManager em){
        QCustomer qCustomer = QCustomer.customer;

        JPAQuery<?> query = new JPAQuery<>(em);
        query.from(qCustomer);

        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomer.email.likeIgnoreCase("c@m.c"));

        JPAQuery<?> where = query.where(builder);
        // This for loop is making it work with Pagable
        query.offset(pageable.getOffset());
        query.limit(pageable.getPageSize());
        PathBuilder<Customer> entityPath = new PathBuilder<>(Customer.class, "customer");
        for (Sort.Order order : pageable.getSort()) {
            PathBuilder<Object> path = entityPath.get(order.getProperty());
            query.orderBy(new OrderSpecifier(Order.valueOf(order.getDirection().name()), path));
        }

        List<Customer> resultList = query.createQuery().getResultList();
    }
}