Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data query dsl how to add order by?

I'm new to Querydsl, I'm working on Spring data and Querydsl to make a dynamic filter, I use the interface: QueryDslPredicateExecutor so I can filter data using different entity fields, now I want to add "order by" to my query based on a BooleanExpression.

This my code:

QPersonData _personInventory = QPersonData.personData;
BooleanBuilder query = new BooleanBuilder();

query.and(_personInventory.status.eq(status));

Then I called my respository interface using the query:

personInventoryRepository.findAll(query, pageable);

My question is how I can apply "order by" to my query object based on different fields on my entity?

like image 580
e2rabi Avatar asked Oct 03 '18 13:10

e2rabi


3 Answers

Thanks all finally this solution work for me :

 QPersonData _personInventory = QPersonData.personData;
 BooleanBuilder query = new BooleanBuilder(); 

 query.and(_personInventory .status.eq(status));
 personInventoryRepository.findAll(query,0, Integer.MAX_VALUE,new QSort(_personInventory.field1.asc(),_personInventory.field2.asc()));   
like image 140
e2rabi Avatar answered Oct 22 '22 10:10

e2rabi


You can add sort to your page information:

 Sort sort = new Sort.Order(Sort.Direction.ASC,"filedname").nullsLast();
 PageRequest pageRequest = new PageRequest(pageNumber, pageSize, sort);
 personInventoryRepository.findAll(query,pageRequest); 
like image 5
Rahim Dastar Avatar answered Oct 22 '22 12:10

Rahim Dastar


Add a method in your repository interface

findByStatus(status)

Then use code block like below

Pageable pageable = new PageRequest(offset, limit, Direction.DESC, "updatedAt");
repository.findByStatus(status, pageable);

if your using spring boot 2.0.0 => then use method

PageRequest.of(....)
like image 4
Vijay Pal Vishwakarma Avatar answered Oct 22 '22 11:10

Vijay Pal Vishwakarma