【问题标题】:Using TIMESTAMPDIFF function on LocalDate in JPA Criteria query在 JPA 标准查询中对 LocalDate 使用 TIMESTAMPDIFF 函数
【发布时间】:2021-09-07 01:39:54
【问题描述】:

我必须编写一个查询来计算两个日期之间的年时差。其中一个日期是从数据库中获取的,而另一个是 LocalDate。以下是我写的代码:

Expression<String> year = new UnitExpression(null, String.class, "YEAR");
LocalDate date=LocalDate.of(2018, 04, 30);
Expression<Integer> timeDiff = builder.function(
            "TIMESTAMPDIFF",
            Integer.class,
            year ,
            propertyListRoot.get("rentStartDate"),
            date);

其中 UnitExpression 是扩展 BasicFunctionExpression 的自定义类。但是,这会产生编译时错误提示

必需的类型表达式>提供的LocalDate

我研究了一下并尝试了

criteriaBuilder.literal(日期)

这解决了编译时错误,但不会计算正确的值。什么是可能的解决方案?我在这里错过了什么?

【问题讨论】:

    标签: mysql spring-boot spring-data-jpa hibernate-criteria timestampdiff


    【解决方案1】:

    我犯的错误是没有将函数的参数转换为Timestamp。这工作正常:

    Expression<Integer> timeDiff = builder.function(
                "TIMESTAMPDIFF",
                Integer.class,
                year,
                propertyListRoot.<Timestamp>get("rentStartDate"),
                builder.literal(Timestamp.valueOf(month))
        );
    

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2012-01-19
      • 1970-01-01
      • 2011-08-14
      相关资源
      最近更新 更多