题
我使用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-使用 ICriteria
和 SetProjections
如下
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;
}
}
现在我的问题是哪个具有更好的性能?为什么?
解决方案
我认为,获得更好的度量的最好方法将如下所述。去下载NHPROF并配置文件。
如果您想要更多的详细信息,请使用生成的SQL,然后通过SQL Server Profiler运行它,以更好地了解其在做什么。
但老实说,如果您的数据库中有任何数量的数据进行类似查询将为您带来可怕的结果。
我强烈建议您在SQL Server中设置全文索引,然后使用以下方式:
注册Freetext并包含NHIBERNATE中的功能。
与Icriteria查询集成的另一个很好的例子是:
http://xlib.wordpress.com/2009/12/04/integrating-freetext-search-in-nhibernate-detached-criteria/
另外,您也可以使用lucene.net进行全文索引。
其他提示
HQL和标准之间没有明显的内在性能差异。他们只是不同的API来表达一个查询,即最终将转换为SQL,仅此而已。
标准(不打算双关语)选择一个API而不是另一个API取决于用法上下文。例如,在您的特殊情况下,我会遵循标准。通过字符串串联构建查询非常容易出错,您必须非常小心不要 容易受到注射攻击. 。至少设置 propertyValue
成为一个 IQuery
范围...
不隶属于 StackOverflow