Querydsl - 分页功能

Querydsl - paging functionality

似乎在 Jpa QueryDsl 中我可以像这样使用分页:

return new JPAQueryFactory(getEntityManager())
    .selectFrom(entity)
    .where(where_clause)
    .orderBy(order_by_clause)
    .offset(pageNumber * 20)
    .limit(20)
    .fetchResults();

问题是:

是的,我知道 Spring-Data 已经为 QueryDsl 提供了分页和接口,但是由于 Spring 不支持的复杂 "order by" 子句-我无法使用的数据:(

这里太晚了,但可能有人会觉得有用。

Is it optimal approach? Does fetchResults load only 20 elements from DB and make count query to get information about total number of entities which are in db?

是 - 它将发出 2 个查询。一个用于使用 where 子句进行计数,另一个用于获取结果。当您有兴趣了解满足条件(where 子句)的记录数以及根据页面大小和偏移量获取数据时,这是需要的。通过使用 .fetchResults(),您应该使用以下方法获取总计数和返回的行数,如下所示。

QueryResults<Tuple> result = query.fetchResults();
int totalCount = result.getTotal();
List<Tuple> rows = result.getResults();

Or maybe there is some option like .page(2).limit(20)?

是 - 如果您只想获取偏移量和页面大小的结果,您应该使用

List<Tuple> rows = query.limit(20).offset(2*20).fetch();

fetch() 方法将仅发出 1 个查询以按指定的页面大小和偏移量获取结果 'limited'。

Querydsl.applyPagination()也可以用

org.springframework.data.domain.PageImpl;
org.springframework.data.domain.Pageable;

Querydsl querydsl = new Querydsl(entityManager, (new PathBuilderFactory()).create(<EntityClass>.class));
JPQLQuery<?> query = new JPAQuery<>(entityManager);

//TODO: prepare your query here 

//Get the count
Long totalElements = query.fetchCount();

//Apply the pagination
List<?> result = querydsl.applyPagination(pageable, query).fetch();

//return a paged response
return new PageImpl<>(result, pageable, totalElements);