Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a JPAQuery with pagination using Spring Data and QueryDSL

I have this request working good with queryDSL :

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

But what is its equivalent if we use it with spring data jpa

ao_respository.findAll(Predicate arg0, Pageable arg1);

Because i want to return a Page and just with querydsl it doesn't implement Page without spring data jpa.

I try to put my where in Predicate arg0 but i got this exception

Undeclared path 'lot '. Add this path as a source to the query to be able to reference it

where lot is declared as QLot lot = QLot.lot;

like image 270
Hayi Avatar asked Sep 15 '25 11:09

Hayi


1 Answers

Returning a 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);

And I created this function to get 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);
}
like image 87
anat0lius Avatar answered Sep 17 '25 04:09

anat0lius