Java 使用Hibernate标准和Oracle处理时间的更好方法是什么?
我想按时间选择实体。 我有一个字段类型为DATE的Oracle DBMS,其中包含日期和时间。这是我的密码。如何按时间标准选择数据Java 使用Hibernate标准和Oracle处理时间的更好方法是什么?,java,oracle,hibernate,time,criteria,Java,Oracle,Hibernate,Time,Criteria,我想按时间选择实体。 我有一个字段类型为DATE的Oracle DBMS,其中包含日期和时间。这是我的密码。如何按时间标准选择数据 Calendar timeCal = new GregorianCalendar(0,0,0,0,0,0); Date timeMin = timeCal.getTime(); timeCal.add(Calendar.HOUR_OF_DAY, 1); Date timeMax = timeCal.getTime(); if (minDate !
Calendar timeCal = new GregorianCalendar(0,0,0,0,0,0);
Date timeMin = timeCal.getTime();
timeCal.add(Calendar.HOUR_OF_DAY, 1);
Date timeMax = timeCal.getTime();
if (minDate != null && maxDate != null)
criteria.add(Restrictions.between("eventDate", minDate, maxDate));
if (onDate != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(onDate);
calendar.add(Calendar.DAY_OF_MONTH, 1);
criteria.add(Restrictions.between("eventDate", onDate, calendar.getTime()));
}
if(minTime!=null&&maxTime!=null){
/*
How to add Restriction on eventDate field, for time only?
if minTime is 3:00 and maxTime is 16:00, must to return
all rows having the time part of their eventDate between
3:00 and 16:00, regardless of the date part
*/
}
您必须使用SQL限制来实现这一点,或者,更可取的是,您必须创建自己的标准实现,这将发出适当的SQL限制 以
org.hibernate.criteria.IlikeExpression
类为例:当它不使用PostgreSQL方言时,它会生成SQL表达式lower(columnName),如?
,其中表达式的参数是value.toString().toLowerCase()
您的标准应该生成类似于
to\u date(to\u char(columnName,'HH24:MI:SS'),'HH24:MI:SS')<?)
的内容,其中表达式的参数是您的最大时间。(当然,对最小时间执行类似的标准)Hibernate HQL有hour
、minute
和second
函数,可以在这种特定情况下使用,因此可以在HQL而不是SQL中执行此操作。因此,您需要一个HQL查询,而不是一个Criteria对象。HQL将看起来像
from tableName
where eventDate between :minDate and :maxDate
and 3600 * hour( eventDate ) + 60 * minute( eventDate ) + second( eventDate )
between :minSeconds and :maxSeconds
您将在此处适当设置:分秒
和:最大秒
参数。使用:maxDate
也要小心逐个出错
有关HQL的更多信息,请访问我找到答案。只需要使用sqlRestriction
criteria.add(
Restrictions.sqlRestriction(
" NUMTODSINTERVAL(EVENT_DATE - TRUNC(EVENT_DATE), 'DAY') BETWEEN NUMTODSINTERVAL (?,'SECOND') AND NUMTODSINTERVAL (?,'SECOND')",
new Object[] { secondsForBegin, secondsForEnd },
new Type[] { StandardBasicTypes.INTEGER, StandardBasicTypes.INTEGER }));
你发布的代码有什么问题?没有在minTime中实现=null&&maxTime=null Expression我们不知道这些条件是什么,以及查询应该做什么。条件应该对eventDate字段添加限制,仅限时间。因此,如果minTime为3:00,maxTime为16:00,则您希望返回eventDate的时间部分在3:00和16:00之间的所有行,而不考虑日期部分,是吗?查询对于hql和仅数据部分来说非常大。