【问题标题】:Cast date and time to DateTime in hibernate query在休眠查询中将日期和时间转换为 DateTime
【发布时间】:2021-02-26 06:04:41
【问题描述】:

我在我的项目中使用带有休眠功能的 Spring Boot。我想知道是否可以在休眠查询中将日期和时间转换为日期时间/时间戳。

问题是什么?我有表`Term`:
id_term|date      |time    |id_appointment|accepted|
-------|----------|--------|--------------|--------|
     45|2020-10-22|11:30:00|             6|       1|
   4247|2020-10-19|19:00:00|             4|       1|
  62648|2020-11-02|08:00:00|              |       0|
  62649|2020-11-02|08:30:00|              |       0|      

如您所见,有datetime 列。我想从当前的“日期时间”获得下一个 25 个免费期限(免费期限意味着 id_appointment 为 NULL)。 目前我有这样的查询:SELECT TOP 25 * FROM Term WHERE id_appointment IS NULL AND time > :currentTime AND date > :currentDate。但它不能正常工作。例如,如果现在是下午 2:15,明天我在上午 11 点到下午 4 点之间有免费期限,则此查询仅在下午 2:15 之后返回免费期限。我正在寻找与此类似的解决方案:SELECT TOP 25 * FROM Term WHERE id_appointment IS NULL AND CAST(date + time) > :currentDateTime。 Java 中Term 类中的字段为LocalDateLocalTime 变量。

【问题讨论】:

    标签: java sql spring-boot hibernate spring-data-jpa


    【解决方案1】:

    我解决了我的问题。正确答案是:

    @Query(value = "SELECT TOP 20 * FROM term WHERE id_appointment IS NULL AND (CAST(date as datetime) + CAST(time as datetime)) > :currentDateTime ORDER BY date ASC, time ASC", nativeQuery=true)
    List<Term> getNext20FreeTerms(@Param("currentDateTime") LocalDateTime currentDateTime);
    

    【讨论】:

      【解决方案2】:

      以上答案对我来说并不完全有效。我在 Hibernate Native Query 中遇到了异常-“语句中的数据类型不兼容” 我必须在日期和时间之间包含一个空格。好吧,我正在使用 SQL Server。这是更新后的查询 -

      @Query(value = "SELECT TOP 20 * FROM term WHERE id_appointment IS NULL AND (CAST(date as datetime) + ' ' + CAST(time as datetime)) > :currentDateTime ORDER BY date ASC, time ASC", nativeQuery=true) 
      List<Term> getNext20FreeTerms(@Param("currentDateTime") LocalDateTime currentDateTime);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 2012-10-18
        • 2012-04-01
        • 2011-04-08
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        相关资源
        最近更新 更多