【问题标题】:Spring JPA specification convert root type to compare successfullySpring JPA规范转换根类型比较成功
【发布时间】:2021-05-11 19:30:18
【问题描述】:

所以我的File 创建 日期是OffsetDateTime 中的时间戳,API 的请求参数是LocalDate,没有任何时间。如果日期相同,我需要比较它们是否相等,从等式中删除时间。

我虽然想做这样的事情,但它不能正常工作。即使是<LocalDate>

private Specification<File> isOfInitiationDate(LocalDate initiationDate) {
    return (Specification<File>) (root, criteriaQuery, criteriaBuilder) ->
            criteriaBuilder.equal(root.<LocalDate>get("created"), initiationDate);
}

我收到:

Parameter value [2021-02-03] did not match expected type [java.time.OffsetDateTime (n/a)]

如果root.get("created) 的日期与LocalDate initiationDate 相同,我如何使此规范返回值?

【问题讨论】:

  • 你能在调试期间在你的 IDE 中计算表达式 get("created") 吗?查看返回的具体类型并相应地进行转换。
  • @TomElias 检查,它是OffsetDateTime,你建议我应该如何投射它以及在哪里投射?

标签: java spring jpa spring-data-jpa


【解决方案1】:

将 OffsetDateTime 转换为 localdate 如下,示例代码如下

OffsetDateTime offsetDateTime=get("created");
Localdate localDate=offsetDateTime.toLocaldate();

criteriaBuilder.equal(localDate, initiationDate);

【讨论】:

  • 感谢您的解决方案。我设法通过这样做root.get("created).as(LocalDate.class) 来修复它,现在一切正常!
【解决方案2】:

我自己设法解决了这个问题。我是这样投的:

root.get("created).as(LocalDate.class)

现在它将两个变量作为LocalDate 进行比较,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 2022-08-12
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2014-08-04
    • 2016-07-22
    • 2018-11-01
    相关资源
    最近更新 更多