首页 > 解决方案 > 在休眠查询中将日期和时间转换为 DateTime

问题描述

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

问题是什么?我有表`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. TermJava中类中的字段是LocalDateLocalTime变量。

标签: javasqlspring-boothibernatespring-data-jpa

解决方案


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

@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);

推荐阅读