假设我有截止日期和提醒时间范围。如何使用Hibernate 3.6条件查询找到截止日期小于当前日期+提醒的那些?换句话说,我想找到我的活动,我已经显示了提醒。当提醒应该以天或毫秒发送时,提醒是一个长标记,以较容易为准。
总结一下,我的实体正在关注:
java.util.Date Event.DueDate
Long Event.Type.Reminder.Before // (in days or millis)
实施例
Today is 2012-06-11.
Included:
DueDate is 2012-06-15 and Before is 30 days.
Excluded:
DueDate is 2012-06-15 and Before is 1 day.
答案 0 :(得分:0)
最终这就是ANSI SQL所谓的日期/时间算术,特别是您正在寻找 INTERVAL 数据类型处理。不幸的是,数据库在支持INTERVAL数据类型方面差异很大。我真的想在HQL中支持这个(可能标准,尽管这依赖于JPA规范委员会的协议)。像我说的那样,困难在于间隔的变化(如果有的话)。
目前最好的选择(通过Hibernate 4.1)是提供在org.hibernate.dialect.function.SQLFunction
注册的自定义功能(Dialect
)(搜索谷歌,看看这是怎么回事已完成)或“自定义函数注册表”(org.hibernate.cfg.Configuration#addSqlFunction
)。您可能希望使用间隔渲染数据库特定的date-arith表示。
以下是使用Oracle NUMTODSINTERVAL
函数的示例:
public class MySqlFunction implements SQLFunction
{
public Type getReturnType(Type firstArgumentType,
Mapping mapping) throws QueryException
{
return TimestampType.INSTANCE;
}
public String render(Type firstArgumentType,
List arguments,
SessionFactoryImplementor factory) throws QueryException
{
// Arguments are already interpreted into sql variants...
final String dueDateArg = arguments.get( 0 );
final String beforeArg = arguments.get( 1 );
// Again, using the Oracle-specific NUMTODSINTERVAL
// function and using days as the unit...
return dueDateArg + " + numtodsinterval(" + beforeArg + ", 'day')";
}
public boolean hasArguments() { return true; }
public boolean hasParenthesesIfNoArguments() { return false; }
}
您可以在HQL中使用它,如:
select ...
from Event e
where current_date() between e.dueDate and
interval_date_calc( e.dueDate, e.before )
其中'interval_date_calc'是您注册SQLFunction的名称。