如何使用 Spring Data 和 QueryDSL 执行带有分页的 JPAQuery

You*_*sef 3 spring hibernate querydsl spring-data spring-data-jpa

我有这个请求工作良好queryDSL

 Iterable<AO> query_result = new JPAQuery(entityManager).from(ao)
            .leftJoin( ao.lots , lot )
            .leftJoin( ao.acs , ac )
              .where(where).distinct()
                .list(ao);
Run Code Online (Sandbox Code Playgroud)

但是如果我们使用它,它的等价物是什么 spring data jpa

ao_respository.findAll(Predicate arg0, Pageable arg1);
Run Code Online (Sandbox Code Playgroud)

因为我想返回 aPage并且只是使用querydsl它不会在Page没有spring data jpa.

我试着把我的wherePredicate arg0但我得到了这个例外

Undeclared path 'lot '. Add this path as a source to the query to be able to reference it
Run Code Online (Sandbox Code Playgroud)

其中lot声明为QLot lot = QLot.lot;

ana*_*ius 7

返回一个Page

JPAQuery query = 
    ...
    .orderBy(getOrderSpecifiers(pageable, MyEntity.class))
    .limit(pageable.getPageSize())
    .offset(pageable.getOffset());

long total = query.fetchCount();
List<MyEntity> content = query.fetch();
return new PageImpl<>(content, pageable, total);
Run Code Online (Sandbox Code Playgroud)

我创建了这个函数来获取OrderSpecifier

private OrderSpecifier[] getOrderSpecifiers(@NotNull Pageable pageable, @NotNull Class klass) {

    // orderVariable must match the variable of FROM
    String className = klass.getSimpleName();
    final String orderVariable = String.valueOf(Character.toLowerCase(className.charAt(0))).concat(className.substring(1));

    return pageable.getSort().stream()
            .map(order -> new OrderSpecifier(
                    Order.valueOf(order.getDirection().toString()),
                    new PathBuilder(klass, orderVariable).get(order.getProperty()))
            )
            .toArray(OrderSpecifier[]::new);
}
Run Code Online (Sandbox Code Playgroud)


You*_*sef 5

我创建了自己的 Page 类并执行如下查询:

    JPAQuery query = new JPAQuery(entityManager).from(ao)               
            .leftJoin( .. ).fetch()
            .leftJoin( .. ).fetch()
            ...
            .where(where)




    MaPage<AO> page = new MaPage<AO>();
    page.number = pageNumber+1;

    page.content = query.offset(pageNumber*pageSize).limit(pageSize).list(ao);

    page.totalResult = query.count();
Run Code Online (Sandbox Code Playgroud)

我的页面类:

public class MaPage<T> {

    public List<T> content;
    public int number;
    public Long totalResult;
    public Long totalPages;
    ...
}
Run Code Online (Sandbox Code Playgroud)

它有效,但我收到此警告

十一月 2014 年 2 月 21 日上午 6:48:54 org.hibernate.hql.internal.ast.QueryTranslatorImpl 列表警告:HHH000104:使用集合提取指定的 firstResult/maxResults;在内存中申请!

  • 当您加入 fetch 时,不能在 SQL 级别应用集合属性分页。 (3认同)
  • 如果您摆脱左连接提取并使用例如集合成员的批量提取,则可以避免此警告。 (2认同)