2

I have a JpaRepository:

public interface PostRepository extends JpaRepository<Entity, Integer>

And I have a default method inside:

Page<Entity> findAllByBookIdAndStatus(Integer bookId, PostStatus postStatus, Pageable pageable);

And the method above doesn't sort my data, just return in no particular order.

So if I want to have my data sorted, can I add some SQL data to this method e.g. ORDER BY ENTITY_ID and to not write new SQL query?

Is it possible and if yes, how can I do it?

Eklavya
  • 17,618
  • 4
  • 28
  • 57
user13566239
  • 23
  • 1
  • 5

3 Answers3

0

Have you checked this post out?

Something like this should work.

Page<Entity> findAllByBookIdAndStatusOrderByIdAsc(
    Integer bookId,
    PostStatus postStatus,
    Pageable pageable);
bonobo
  • 132
  • 2
  • 10
0

There are two ways of doing this :

  • writing a query with the @Query anotation and using the proper syntaxe to order the response (depends of the DBMS you're using)
  • or you can itterate the reponse in the service layer to order them

personnaly i would use the first method

KASMI G.
  • 116
  • 11
0

You can add sorting info into pageable object with page and size when create pageable object.

Pageable pageable = new PageRequest(1, 10, new Sort(Sort.Direction.ASC, "ENTITY_ID"))
Eklavya
  • 17,618
  • 4
  • 28
  • 57