2

我使用 NHibernate 用两种方法编写了相同的查询:

1-通过使用HQL如下

public long RetrieveHQLCount<T>(string propertyName, object propertyValue)
{
    using (ISession session = m_SessionFactory.OpenSession())
    {
        long r = Convert.ToInt64(session.CreateQuery("select count(o) from " + typeof(T).Name + " as o" + " where o." + propertyName + " like '" + propertyValue + "%'").UniqueResult());
        return r;
    }
}

2-通过使用ICriteriaSetProjections如下

public long RetrieveCount<T>(string propertyName, object propertyValue)
{
    using (ISession session = m_SessionFactory.OpenSession())
    {
        // Create a criteria object with the specified criteria
        ICriteria criteria = session.CreateCriteria(typeof(T));
        criteria.Add(Expression.InsensitiveLike(propertyName, propertyValue))
            .SetProjection(Projections.Count(propertyName));

        long count = Convert.ToInt64(criteria.UniqueResult());

        // Set return value
        return count;
    }
}

现在我的问题是哪个性能更好?为什么?

4

2 回答 2

2

我认为获得更好的指标的最佳方法是如here所述。去下载 nhProf 并分析它。

http://nhprof.com/

如果您想了解更多详细信息,请获取生成的 sql,然后通过 SQL Server 分析器运行它,以更好地了解它在做什么。

但老实说,如果您的数据库中有任何数量的数据,执行 LIKE 查询会给您带来可怕的可怕结果。

我强烈建议您在 SQL Server 中设置全文索引,然后使用它:

http://nhforge.org/blogs/nhibernate/archive/2009/03/13/registering-freetext-or-contains-functions-into-a-nhibernate-dialect.aspx

注册自由文本并包含 nHibernate 中的函数。

与 ICriteria 查询集成的另一个很好的例子是:

http://xlib.wordpress.com/2009/12/04/integrating-freetext-search-in-nhibernate-detached-criteria/

或者,您也可以使用 Lucene.NET 进行全文索引。

于 2010-05-06T14:13:16.093 回答
2

HQL 和 Criteria 之间没有显着的内在性能差异。它们只是表达查询的不同 API,最终将被转换为 SQL,仅此而已。

选择一个 API 而不是另一个 API 的标准(没有双关语)取决于使用上下文。例如,在您的特定情况下,我会选择 Criteria。从字符串连接构建查询非常容易出错,您必须非常小心,以免受到注入攻击。至少将 设置propertyValueIQuery参数...

于 2010-05-06T14:32:45.613 回答