1

I want to prepare custom query for getting sorted list of objectes from repository. I would like to have only one query, where I put only name of column as argument. What should I add after "Order by"?

@Query("FROM NoteEntity n where n.user.id = ?2 ORDER BY :columnName ASC")
List<NoteEntity> getNotesSortedByColumn(String columnName, String userID);

Following query return list of objects but without any sorting.

Lulex97
  • 231
  • 1
  • 10
  • Please refer https://stackoverflow.com/questions/47407043/spring-data-jpa-pass-column-name-and-value-as-parameters#48492077 & https://stackoverflow.com/questions/42152468/how-to-add-custom-column-name-spring-data-jpa & https://stackoverflow.com/questions/31554479/how-can-i-add-columns-dynamically-to-a-spring-data-jpa-query – Sibin Rasiya May 15 '22 at 18:31
  • 1
    It has to look like `getNotesSortedByColumn(String userID, Pageable pageable)` where the `Pageable` is the Spring Data class so there's no explicit `order by` is even required. Also, you can use `Sort` instead. – WildDev May 15 '22 at 21:53

1 Answers1

1

Ok, thanks for help. I used "sort" to the custom query and everythingworks. In repository:

@Query("FROM NoteEntity n where n.user.id = ?1")
List<NoteEntity> getNotesSortedBy(String userID, Sort sort);

and in service:

List<NoteEntity> sortedNotes = noteEntityRepository.getNotesSortedBy(
            userID, Sort.by(Sort.Direction.ASC, "columnName"));
Lulex97
  • 231
  • 1
  • 10