如何实现基于Java SpringBoot中的Date排序?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (396)

这里是我的API服务,需要一个使用API的计算列表,根据日期的降序排序它,而当前的实现是它的升序

    /*
     * Get  Risk Evaluation based on id
     */
    public List<RiskEvaluation> getByTest(String test) {
        return riskEvaluationRepository.findByTest(test);
    }

控制器是

@GetMapping("/{test}")
    @ApiOperation(value = "gets", notes = "Get all the Risk Assessments based on TEST.", response = RiskEvaluation.class, tags = {"GetsAllRisksforaTEST",})
    public List<RiskEvaluation> getByTest(@PathVariable("test") String test) {
        return scoringService.getByTest(test);
    }

使用此API获得的当前输出是

{
        "accountID": null,
        "bap_id": "cccccccccc",
        "release_version": "1.9",
        "risk_level": "Medium",
        "risk_score": 2,
        "createdOn": 1533584332466,
        "updatedOn": 1533584332466,
        "id": "8340f05c-06c4-430a-bbbd-a53d0ce60dea"
    },
    {
        "accountID": null,
        "bap_id": "cccccccccc",
        "release_version": "1.9",
        "risk_level": "Medium",
        "risk_score": 2,
        "createdOn": 1533584551115,
        "updatedOn": 1533584551115,
        "id": "ae175b92-805d-46b5-8f67-95795e232057"
    },
    {
        "accountID": null,
        "bap_id": "cccccccccc",
        "release_version": "2.0",
        "risk_level": "Medium",
        "risk_score": 2,
        "createdOn": 1533584718584,
        "updatedOn": 1533584718584,
        "id": "d19177ef-b8c4-4951-bbdb-4e4d7274be81"
}
提问于
用户回答回答于

可能需要使用JpaRepository或CrudRepository,在任何findAll中,都可以使用:

@Query("SELECT r FROM RiskEvaluation r ORDER BY createdOn ASC")
List<RiskEvaluation> findAll();

List<RiskEvaluation> findAllOrderByCreatedOnAsc();
interface PersonRepository extends Repository<User, Long> {

  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

  // Enables the distinct flag for the query
  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
  List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

  // Enabling ignoring case for an individual property
  List<Person> findByLastnameIgnoreCase(String lastname);
  // Enabling ignoring case for all suitable properties
  List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

  // Enabling static ORDER BY for a query
  List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
  List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}
用户回答回答于

可以用以下代码试试:

int page = 0, size = 10;

Pageable pageable = PageRequest.of(page, size, new Sort("createdOn", Sort.Direction.DESC));

扫码关注云+社区

领取腾讯云代金券