我想将org.springframework.data.domain.Pageable
与com.querydsl.jpa.impl.JPAQuery
一起使用,或者是否有可靠的解决方法来使Pageable与JPAQuery一起使用?
答案 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();
}
}