Search code examples
springspring-bootpageable

Spring boot - subtraction inside sortBy (Pageable)


Is it possible to subtract two fields(numbers) inside sortBy in pagerequest like this??

PageRequest.of(page, size, Sort.Direction.ASC, "price-discount")

. This is error i get..

Sort expression 'price-discount: ASC' must only contain property references or aliases used in the select clause. If you really want to use something other than that for sorting, please use JpaSort.unsafe(…)!


Solution

  • Creates a new PageRequest with sort direction and properties applied.

    PageRequest.of(page, size, Sort.Direction.ASC, "price", "discount");
    

    OR

    Creates a new PageRequest with sort parameters applied.

    Sort sort = Sort.by(
        Sort.Order.asc("price"),
        Sort.Order.desc("discount"));
    PageRequest.of(page, size, sort);