Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify default sort in Spring Data @Repository find method?

Is below the only way (not so "clean" IMHO)? I'd expect something like @SortDefault and @PageableDefault, but it's only for (REST) controllers and not applicable to Spring Data REST.

@Query("SELECT e FROM FacebookPost e WHERE e.commentsPaging.next IS NOT NULL ORDER BY e.creationTime ASC")
Page<FacebookPost> findByCommentsHasNext(Pageable pageable);

Additionally:

  1. How to specify multiple columns for default sorting?
  2. How to specify calculated column(s), i.e. involving CASE WHEN or functions (which can be indexed in PostgreSQL)?
like image 648
Hendy Irawan Avatar asked Sep 07 '25 19:09

Hendy Irawan


1 Answers

I'm not sure if @SortDefault is what you're looking for but you can directly specify the type of ordering you'd like with the repository method name. For example, from reading your query, I'd name the method something as follows:

Page<FaceBookPost> findByCommentHasNextOrderByCreationTimeAsc(Pageable pageable); 

If you dictate elsewhere that the field commentsPaging cannot be null, I don't think there would even be a need for a @Query above your method name since Spring will automatically go and perform the query for you.

like image 78
mengchengfeng Avatar answered Sep 10 '25 06:09

mengchengfeng