Patrick Grimard
Patrick Grimard

Reputation: 7126

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 :)

Upvotes: 4

Views: 8064

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

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

Upvotes: 14

Related Questions