spring boot jpa 使用多個欄位排序

URL Link //n.sfs.tw/14654

2020-06-06 21:24:37 By igogo

 

我有一entity - Team

資料欄下如下

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String contestitem;
    private String schoolname;
    private String username;

    private String membername;
    private String instructor;

    private String location;

    private String description;
    private String comments;

 

搜尋時想先依location排序,  再依schoolname 最後依 contestitem 排序

做法, 在 TeamRepository裡加上

public interface TeamRepository extends CrudRepository<Team, Long> {

    List<Team> findAll(Sort sort);
}

 

查詢的語法如下

List<Team> teams = teamRepository.findAll(Sort.by("location").and(Sort.by("schoolname")).and(Sort.by("description").and(Sort.by("contestitem"))));
       

 

參考:

https://bezkoder.com/spring-data-sort-multiple-columns/