如何从条件中的日期时间中提取小时数?

How to extract hour from datetime in criteria?

我必须写这样的东西:

SELECT * FROM foo WHERE HOUR(field) = 10

其中字段是日期时间。

我想忽略日期 - 出于统计目的,我只需要提取发生在 10:00 和 10:59 之间的事件。

我知道,我可以:

String sql = "HOUR(CREATED_AT) = 10";
criteria.add(Expression.sql(sql));

但我想使用休眠机制,而不是 SQL 字符串。

有什么办法吗?

简单的解决方案 - 应该像这样工作:

var hourProjection = Projections
     .SqlProjection(" DATEPART(HOUR,field) as hour "  // the left side of the expression
                   , new[] {"hour"}          // alias  
                   , new IType[] {NHibernateUtil.Int32}); // type is int

criteria.Add(Expression.Eq(hourProjection, myValue)); // myValue = 10

检查:How to compare datepart Month using Nhibernate Criteria?

NHibernate-ish 解决方案 - 如果我们想广泛使用该函数 HOUR,我们可以使用其定义扩展 Dialect

public class CustomMsSql2012Dialect : MsSql2012Dialect
{
    public CustomMsSql2012Dialect()
    {
        RegisterFunction("HOUR", 
            new SQLFunctionTemplate(NHibernateUtil.Class, "DATEPART(HOUR,?1)"));
    }
}

并将其注入配置:

<property name="dialect">MyLib.CustomMsSql2012Dialect,MyLib</property>

然后这样消费:

var hourFunctionProjection = Projections
  .SqlFunction("HOUR", NHibernateUtil.Int32, Projections.Property("Field"));

restrictions.Add(Restrictions.Eq(hourFunctionProjection, 10));

检查:Using SQL CONVERT function through nHibernate Criterion

这从日期时间获取小时数

select DATEPART(HOUR, field) from tableName