【问题标题】:Spring Boot Search Data by Date (formated in ZonedDateTime)Spring Boot 按日期搜索数据(以 ZonedDateTime 格式)
【发布时间】:2019-04-18 10:44:55
【问题描述】:

我想获取在特定日期提交的表单列表。日期将由管理员在搜索框中传递(从前端它将是字符串,但在后端它是 ZonedDateTime)。

我在 Repository 中写了方法:

List<AdmissionForm> findByDateContains(ZonedDateTime datePart);

方法形成参考:https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-from-method-names/

我的Service类后台逻辑是这样的:

@Transactional(readOnly = true)
public List<AdmissionFormDTO> findByDate(ZonedDateTime datepart){
    return admissionFormRepository.findByDateContains(datepart).stream()
        .map(admissionFormMapper::toDto)
        .collect(Collectors.toList());
}

而我的资源端点是这样的:

@GetMapping("/admissionForms/date")
@Timed
public List<AdmissionFormDTO> findByDate(@RequestParam("date") String date){
    log.debug("REST request to get AdmissionForms by searchTerm :" + date);
    //String to ZonedDateTime method conversion from seperate class
    ZonedDateTime zDate = SupportUtils.convertStringDateToZoneDateTime(date);
    return admissionFormService.findByDate(zDate);
}

我已经尝试过使用字符串搜索词,它工作正常,但在使用日期搜索时遇到了问题。

我得到了这样的异常:

java.lang.IllegalArgumentException: Parameter value [%2018-11-20T00:00Z%] did not match expected type [java.time.ZonedDateTime (n/a)]' and exception = 'Parameter value [%2018-11-20T00:00Z%] did not match expected type [java.time.ZonedDateTime (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [%2018-11-20T00:00Z%] did not match expected type [java.time.ZonedDateTime (n/a)]'

进行一些更正,以便我可以按预期按日期进行搜索。

已编辑: 我将数据类型从 ZoneDateTime 更改为 LocalDate 并相应地解决如下(现在跳过时间):

我的存储库代码:

List<AdmissionForm> findByDate(LocalDate datePart);

我的服务等级:

@Transactional(readOnly = true)
public List<AdmissionFormDTO> findByDate(String datepart){
    LocalDate localDatePart = SupportUtils.convertStringDateToLocalDate(datepart);
    return admissionFormRepository.findByDate(localDatePart).stream()
        .map(admissionFormMapper::toDto)
        .collect(Collectors.toList());
}

我的资源入口点:

@GetMapping("/admissionForms/date")
@Timed
public List<AdmissionFormDTO> findByDate(@RequestParam("date")String date){
    log.debug("REST request to get AdmissionForms by searchTerm :{}",date);
    return admissionFormService.findByDate(date);
}

感谢您的建议,但找不到与 ZondDateTime 合作的方法,因此我们稍微更改了要求。希望其他人能从这里的问题和建议的答案中得到帮助。

【问题讨论】:

  • 你能分享一下你想点击的uri吗?
  • 它在我的本地服务器中,在外面不可用。帮不了那个:(
  • 我提出了一个答案。可以帮你解决这个问题吗?

标签: java spring spring-boot spring-filter


【解决方案1】:

使用DateTimeFormat注解默认处理ISO yyyy-MM-dd'T'HH:mm:ss.SSSZ日期时间格式:

public List<AdmissionFormDTO> findByDate(
          @RequestParam("date") @DateTimeFormat ZonedDateTime date) {
  return admissionFormService.findByDate(date);
}

如果您的日期不包含示例中的秒字段,您应该进一步自定义 @DateTimeFormat

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多