Set default sort order in Pageable request - java

I want to use this code with specification-arg-resolver with #PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) in order to implement search and to set sort order but it's not working. I tried this:
#GetMapping("find")
public Page<PaymentTransactionsDTO> getAllBySpecification(
#PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC)
#And({
#Spec(path = "unique_id", spec = LikeIgnoreCase.class)
}) Specification<PaymentTransactions> specification,
Pageable pageable
) {
return transactionService.getAllBySpecification(specification, pageable));
}
Do you know how I can set the sort order with annotations into the above code>

I don't know the library but I strongly expect the #DefaultPageable annotation needs to go on the Pageable argument.

Related

JPA Pageable Sort order case sensitive

I am using JpaRepository Pageable query for pagination. All the things are working fine except the sort field case sensitive issue. Following query is used for getting list.
Pageable pageable = null;
if (paginationRequestDTO.getSortOrder().equalsIgnoreCase("desc"))
pageable = new PageRequest(page, size, Sort.Direction.DESC, sortfiled);
else
pageable = new PageRequest(page, size, Sort.Direction.ASC, sortfiled);
Page<Audi> audiPage = null;
audiencePage = audiRepository.search(paginationRequestDTO.getSearchKey(), pageable);
Audi table values are: apple,az,Ajay,Bala.
when i search with sortorder of asc and sort field name,
original output : Ajay,Bala,apple,az.
Expected output: Ajay,apple,az,Bala.
I am using mysql database. table engine - Innodb,characterst-utf8,collate-utf8_bin.
Please note that its not duplicate question.i didn't get exact answer for this question.thanks in advance.
Edited: as harsh pointed out correctly, this needs to be solved on database level, using correct collation. This is important, because you probably want to have an index on the sort column for best performance.
But there are other use cases, which could combine filtering together with sorting by something other, than a pure column value, e.g. by length of description, sum or average of a column, etc. For that reason, I am including a JPA solution:
I struggled with this recently and I am afraid, that the Pageable interface does not support this out of box.
The solution was to use EntityManager, CriteriaBuilder, CriteriaQuery, Specification and implement the paging manually. You can find the solution here.
You need to construct the Page object manually:
public Page<Audi> getPage(int pageNumber, int pageSize, String descriptionFilter, Sorting sorting) {
return new PageImpl<>(
getPageItems(pageNumber, pageSize, descriptionFilter, sorting),
PageRequest.of(pageNumber, pageSize, Sort.by(Sort.Direction.ASC, sorting.name())),
getTotalCount(descriptionFilter)
);
}
getPageItems selects the page using LIMIT and OFFSET
private List<Audi> getPageItems(int pageNumber, int pageSize, String descriptionFilter, Sorting sorting) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Audi> query = cb.createQuery(Audi.class);
Root<Audi> root = query.from(Audi.class);
query.where(createSpecification(descriptionFilter).toPredicate(root, query, cb));
if (sorting.equals(Sorting.descriptionCaseInsensitive)) {
query.orderBy(cb.asc(cb.lower(root.get("description"))));
} else {
throw new UnsupportedOperationException("Unsupported sorting: " + sorting.name());
}
query.select(root);
return em.createQuery(query)
.setFirstResult(pageNumber * pageSize)
.setMaxResults(pageSize)
.getResultList();
}
getTotalCount selects count(distinct(*)),
private long getTotalCount(String descriptionFilter) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> query = cb.createQuery(Long.class);
Root<Audi> root = query.from(Audi.class);
query.where(createSpecification(descriptionFilter).toPredicate(root, query, cb));
query.select(cb.countDistinct(root));
// getSingleResult can return null, if no rows fulfill the predicate
return Optional.ofNullable(em.createQuery(query).getSingleResult()).orElse(0L);
}
Both reuse the same predicate, which filters rows:
private Specification<Audi> createSpecification(String descriptionFilter) {
return Specification.where(
(root, query, criteriaBuilder) ->
criteriaBuilder.like(criteriaBuilder.lower(root.get("description")), "%" + descriptionFilter.toLowerCase() + "%")
);
}

Spring Pageable PageRequest order by doesn't work

I use spring pageable for pagination.
#Transactional(readOnly = true)
#Override
public List<Node> getPageableList(int pageNumber, int pageSize) {
PageRequest pageRequest = new PageRequest(pageNumber, 15, Sort.Direction.DESC, "idNode");
return nodeRepository.getNodesByPage(pageRequest);
}
As you can see , I want to sort my list by "idNode". But still my list sorted by name. I use jquery datatable. Maybe it change in client side my sorting. How I can solve it ?
Thanks in advance.

Creating Pagination in Spring Data JPA

I am trying to implement pagination feature in Spring Data JPA.
I am referring this Blog
My Controller contains following code :
#RequestMapping(value="/organizationData", method = RequestMethod.GET)
public String list(Pageable pageable, Model model){
Page<Organization> members = this.OrganizationRepository.findAll(pageable);
model.addAttribute("members", members.getContent());
float nrOfPages = members.getTotalPages();
model.addAttribute("maxPages", nrOfPages);
return "members/list";
}
My DAO is following :
#Query(value="select m from Member m", countQuery="select count(m) from Member m")
Page<Organization> findMembers(Pageable pageable);
I am able to show first 20 records, how do I show next 20???
Is there any other pagination example that I can refer??
The constructors of Pageable are deprecated, use of() instead:
Pageable pageable = PageRequest.of(0, 20);
I've seen similar problem last week, but can't find it so I'll answer directly.
Your problem is that you specify the parameters too late. Pageable works the following way: you create Pageable object with certain properties. You can at least specify:
Page size,
Page number,
Sorting.
So let's assume that we have:
PageRequest p = new PageRequest(2, 20);
the above passed to the query will filter the results so only results from 21th to 40th will be returned.
You don't apply Pageable on result. You pass it with the query.
Edit:
Constructors of PageRequest are deprecated. Use Pageable pageable = PageRequest.of(2, 20);
Pageable object by default comes with size 20, page 0, and unsorted
So if you want the next page in front end the url can be sent with query params page, size,sort and these u can test it on postman.
You can use Page, List or Slice.
If you dont need the number of pages, and only need to know if the next page exists, use Slice, since it does not do the "count" query:
for (int i = 0; ; i++) {
Slice<Organization> pageOrganization = organizationRepository.find(PageRequest.of(0, 100));
List<Organization> organizationList = pageOrganization.getContent();
for (Organization org : organizationList) {
// code
}
if (!pageOrganization.hasNext()) {
break;
}
}

Spring #PageableDefault default direction changes after passing sort

Given I have this argument in my #RestController GET method:
#PageableDefault(size = 20, sort = "updated_at", direction = Direction.DESC)
When I GET without specifying sort then everything is fine: sort == update_at and direction == DESC.
But when I GET ...?page=1&size=33&sort=asdasd it ignores default direction and sets it to ASC.
Did not get any results of this being a bug. Is it not ?
#PageableDefault() has defaut direction ASC value, you can add as following
#SortDefault.SortDefaults({
#SortDefault(sort = "name", direction = Sort.Direction.DESC)
})
So the request controller look like
public ResponseEntity<Page<Brand>> findAll(
#PageableDefault(sort = { "name", "displayOrder" }, value = 10)
#SortDefault.SortDefaults({
#SortDefault(sort = "name", direction = Sort.Direction.DESC) })
Pageable pageable) {
Page<Brand> brandPage = brandService.findAll(pageable);
}

QueryDSL & Hibernate-Search with Lucene Analyzers

I configured Hibernate-Search to use my custom analyzer when indexing my entities. However when I try and search with QueryDSL's Hibernate-Search integration, it doesn't find entities, but if I use straight hibernate-search it finds something.
#AnalyzerDef(name = "customanalyzer",
tokenizer = #TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
#TokenFilterDef(factory = LowerCaseFilterFactory.class),
#TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
#Parameter(name = "language", value = "English")
})
})
#Analyzer(definition = "customanalyzer")
public abstract class Post extends BaseEntity {}
I indexed an entity with a title of "the quick brown fox jumped over the lazy dog".
These work…
List articlePosts = fullTextEntityManager.createFullTextQuery(queryBuilder.keyword().onFields("title").matching("jumped").createQuery(), ArticlePost.class).getResultList(); // list of 2
List articlePosts = fullTextSession.createFullTextQuery(queryBuilder.keyword().onFields("title").matching("jumped").createQuery(), ArticlePost.class).getResultList(); // list of 2
This does not…
SearchQuery<ArticlePost> query = new SearchQuery<ArticlePost>(this.entityManagerFactory.createEntityManager().unwrap(HibernateEntityManager.class).getSession(), post);
List articlePosts = query.where(post.title.contains("jumped")).list() // empty list
But a search with how it is likely stored in Lucene (probable result of SnowballPorter), then it works…
SearchQuery<ArticlePost> query = new SearchQuery<ArticlePost>(this.entityManagerFactory.createEntityManager().unwrap(HibernateEntityManager.class).getSession(), post);
List articlePosts = query.where(post.title.contains("jump")).list() // list of 2
So it seems like when using QueryDSL, that the analyzer isn't being run before it does the query. Can anyone confirm this is the problem, and is there anyway to have them automatically run before QueryDSL runs the query?
Regarding your question, the analyzer is applied per default when using the query DSL. In most cases it makes sense to use the same analyzer for indexing and searching. For this reason the analyzer is applied per default unless 'ignoreAnalyzer' is used.
Why your second example does not work I cannot tell you. SearchQuery is not part of the Hibernate Search or ORM API. It must be an internal class of your application. What's happening in this class? Which type of query is it using?

Categories

Resources