Hendy Irawan
Hendy Irawan

Reputation: 21384

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

Upvotes: 4

Views: 1669

Answers (1)

mengchengfeng
mengchengfeng

Reputation: 295

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.

Upvotes: 2

Related Questions