Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Pageable breaking Spring Data JPA OrderBy

I have a simple JpaRepository with a finder that returns records ordered by a property named "number" in descending order. The "number" property is also the @Id of my entity. This works just fine, however there's thousands of records, so I want to return a Page instead of a List.

@Repository
public interface ReceiptRepository extends JpaRepository<Receipt, BigDecimal> {

    @Query
    public List<Receipt> findByStorerOrderByNumberDesc(String storer);
}

If I change my finder to something like the following, the sorting no longer works. I've tried using the sort capability of the Pageable argument, but it didn't work. Also removed the OrderByNumberDesc, but same result.

@Repository
public interface ReceiptRepository extends JpaRepository<Receipt, BigDecimal> {

    @Query
    public Page<Receipt> findByStorerOrderByNumberDesc(String storer, Pageable pageable);
}

EDIT - added controller method

The following is my controller method.

@RequestMapping(method = RequestMethod.GET, produces = {"application/json"})
public PagedResources<Receipt> receipts(Pageable pageable, PagedResourcesAssembler assembler) {
    Page<Receipt> receipts = receiptRepository.findByStorer("003845", pageable);
    return assembler.toResource(receipts, receiptResourceAssembler);
}

I feel I'm missing something very basic here.

I'm using Spring Data JPA 1.5.2 and Commons 1.7.2.

Thanks :)

like image 969
Patrick Grimard Avatar asked Oct 23 '25 14:10

Patrick Grimard


1 Answers

Add the sort to your Pageable when you create it:

e.g.

Pageable pageable ...;
pageable.getSort().and(new Sort(Direction.ASC, "prop1", "prop1"));

or in Spring MVC you can do:

@RequestMapping(method = RequestMethod.GET, produces = {"application/json"})
public PagedResources<Receipt> receipts(@PageableDefaults(sort = { "x",
            "y", "z" }, value = 10)Pageable pageable, PagedResourcesAssembler assembler) {
    Page<Receipt> receipts = receiptRepository.findByStorer("003845", pageable);
    return assembler.toResource(receipts, receiptResourceAssembler);
}
like image 197
Alan Hay Avatar answered Oct 26 '25 03:10

Alan Hay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!