【发布时间】:2017-11-01 16:58:10
【问题描述】:
我有一个带有 LocalDateTime 字段的 JPA 实体 TimeSlot,名为 startDateTime:
@Entity
public class TimeSlot {
private LocalDateTime startDateTime;
...
}
我在 WildFly 10.1 上使用 Hibernate。如何查询startDate和endDate之间的startDateTime的所有实体?
private List<TimeSlot> getTimeSlotsByStartDateEndDate(LocalDate startDate, LocalDate endDate) {
return entityManager.createNamedQuery("TimeSlot.findByStartDateEndDate", TimeSlot.class)
.setParameter("startDate", startDate)
.setParameter("endDate", endDate).getResultList());
}
此查询失败,因为时间戳不是日期:
@NamedQueries({
@NamedQuery(name = "TimeSlot.findByStartDateEndDate",
query = "select t from TimeSlot t" +
// fails because a timestamp is not a date
" where t.startDateTime between :startDate and :endDate"),
})
【问题讨论】:
-
似乎至少有些 DB 不喜欢在
BETWEEN运算符中混合 DATE 和 DATETIME/TIMESTAMP。您正在传递LocalDates(startDate和endDate),Hibernate 显然将其转换为 DATE,而t.startDateTime是一个 TIMESTAMP。我可以想到 2 个解决方案(但目前无法验证):(1)在 Java 中将LocalDate转换为LocalDateTime或(2)使用 JPA 的FUNCTION并将 DATE 转换为数据库中的 TIMESTAMP,使用底层数据库的特定于数据库的功能。我会选择(1)。祝你好运:) -
1) 意味着知道一天的第一个和最后一个时间戳是什么。闰秒使这不那么有趣。我会先调查 2)。
-
而调用的 SQL 是什么?