我有一个带有DATE列的Oracle数据库。此列中的示例值为15/12/2014 15:20:15
,格式为DD/MM/YYYY HH:MM:SS
。
我在java Entity类中定义了如下列:
@Column(name = "SVC_EVENT_END_DTTM", columnDefinition = "timestamp")
private Date dateTime;
以下HQL查询有效:
public List<ServiceEventLogEntity> getServiceEventLogEntries(DateTime from,
DateTime to) {
Query query = getSession().createQuery("FROM ServiceEventLogEntity e "
+ "WHERE e.dateTime between :start and :end "
+ "ORDER BY e.dateTime");
query.setDate("start", from.toDate());
query.setDate("end", to.toDate());
query.setMaxResults(100);
if(to.isBefore(new DateTime())) {
// Only caching results for queries in the past.
// Otherwise we could cache incomplete results when
// the end of the query range is in the future
query.setCacheable(true);
}
try {
return (List<ServiceEventLogEntity>) query.list();
} catch (HibernateException hex) {
hex.printStackTrace();
}
return null;
}
但是,这似乎仅在开始和结束时间跨越一天转换时起作用,请参阅下面的跟踪消息:
[http-8080-1] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [DATE] - Sat Dec 13 23:35:00 GMT 2014
[http-8080-1] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [DATE] - Sun Dec 14 00:35:00 GMT 2014
我猜这是因为我的DATE
个对象只代表一天而且没有时间元素。我想能够在几分钟/小时而不是几天查询。我尝试了各种方法,例如使用setTimestamp
代替setDate
,但这最终会导致查询永远不会返回结果,即使在更窄的时间窗口(5分钟)内也是如此
如何修改我的实体或我的查询,以便我可以更精细地使用,以便按分钟或小时而不是按天查询?
答案 0 :(得分:3)
尝试使用:
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "SVC_EVENT_END_DTTM")
private Date dateTime;
来自Temporal源代码的一些javadoc说:
[...]必须为持久字段指定此注释 或者类型为java.util.Date和的属性 java.util.Calendar [...]
如果您不需要毫秒,那么您可以在列中使用Oracle的DATE
类型(最多几秒)。当您需要millis时,必须使用Oracle的TIMESTAMP类型。
==编辑==
另外,您应该使用query.setTimestamp()
代替query.setDate()
。我检查了org.hibernate.Query
来源,并说:
/**
* Bind the date (time is truncated) of a given Date object
* to a named query parameter.
*
* @param name The name of the parameter
* @param date The date object
*/
public Query setDate(String name, Date date);
但
/**
* Bind the date and the time of a given Date object to a named query parameter.
*
* @param name The name of the parameter
* @param date The date object
*/
public Query setTimestamp(String name, Date date);