Spring Pageable PageRequest order by doesn't work - java

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.

Related

Set default sort order in Pageable request

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.

Spring Data Pagination returns wrong number of content as it is requested

currently I am developing an api which uses Spring Data Pagination and I came to the problem that I passing a Pageable object as a request to my repository with which page I want to receive and how many elements should be on it. And with that my object looks like: Pageable pageable = PageRequest.of(0, 2); - so I want first page with two elements. In my database are 3 objects so therefore there will be 2 pages. But what ide shows me is: screenshot. Can anyone tell me why it shows that content is an array of 3 elements but actually I asked for 2 elements?
#Override
public List<NotificationDto> getLast30NotificationsFor(ApplicationUser user) {
Pageable pageable = PageRequest.of(0, 2);
Page<Notification> first30ByOwnerIdOrderByCreatedAtDesc = notificationRepository.findFirst30ByOwnerIdOrderByCreatedAtDesc(user.getId(), pageable);
List<Notification> notifications = new ArrayList<>(first30ByOwnerIdOrderByCreatedAtDesc.getContent());
return notifications.stream()
.map(NotificationToDtoMapper::map)
.collect(toList());
}
Try:
#Override
public List<NotificationDto> getLast30NotificationsFor(ApplicationUser user) {
Pageable page = PageRequest.of(0,2, Sort.by("createdAt").descending());
return notificationRepository.findByOwnerId(user.getId(), page)
.getContent()
.stream()
.map(NotificationToDtoMapper::map)
.collect(toList());
}

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() + "%")
);
}

SpringDataMongo MongoRepository pageable not sorted with geo-spatial method

I am facing a problem with sorting from Pageable with geo-spatial method in MongoRepository
With the following code I am able to retrieve first requestVo.per_page records when requestVo.page is 0. However the list is not sorted by title.
Another thing I have noticed is that the same PageRequest object is able to give me the sorted pageable list with photoRepository.findAll. Any help is appreciated!
LinkedList<Photo> photos= new LinkedList<Photo>();
PageRequest request = new PageRequest(requestVo.page, requestVo.per_page,Direction.ASC,"title");
for (GeoResult<Photo> photoResult : photoRepository.findByLocationNear(point, distance,request).getContent()) {
photos.add(photoResult.getContent());
}
return photos;
Turns out that GeoResult is blocking the sorting. Working perfect when I just return collection of Photo.
LinkedList<Photo> photos= new LinkedList<Photo>();
PageRequest request = new PageRequest(requestVo.page, requestVo.per_page,Direction.ASC,"title");
for (Photo photoResult : photoRepository.findByLocationNear(point, distance,request)) {
photos.add(photoResult);
}
return photos;

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;
}
}

Categories

Resources