我正在使用NHibernate并且我有一个我想要运行的查询,其中包括返回整个表格以及count
和group by
。从我在网上看到的内容,你不能用NHibernate Criteria做到这一点。
为了解决这个问题,我正在使用命名查询:
SELECT id, COUNT(id) AS myCount
FROM foo INNER JOIN bah
ON foo.id = bah.fooId
WHERE foo.Name LIKE :name
GROUP BY fooId
当我只想传递一个参数时,这可以正常工作。
我实际想要实现的目标是:
SELECT id, COUNT(id) AS myCount
FROM foo
INNER JOIN bah ON foo.id = bah.fooId
WHERE foo.Name LIKE :name1
OR foo.Name LIKE :name2
OR foo.Name LIKE :name3
GROUP BY fooId
参数的数量是可变的,因此可能有2或3或4个我想要匹配的名称。
我使用以下代码的标准解决了这个问题:
ICriteria criteria = session.CreateCriteria(typeof (Foo)).CreateCriteria("Bah");
Disjunction disjunction = Restrictions.Disjunction();
foreach (Foo foo in fooToFind)
{
disjunction.Add(Restrictions.Like("Name", "%" + Foo.Name + "%"));
}
criteria.Add(disjunction);
result = criteria.List<Foo>();
(就像我上面所说的那样:看起来我不能使用它,因为我不能将计数作为回报的一部分返回。)
所以我尝试使用query.SetParameterList
:
IQuery query = session.GetNamedQuery("myNamedQuery");
query.SetParameterList("name", new string[] {"eeeny", "meeny"});
然而这似乎给了我sql:
SELECT id, COUNT(id) AS myCount
FROM foo
INNER JOIN bah ON foo.id = bah.fooId
WHERE foo.Name LIKE 'eeny','meeny'
GROUP BY food
所以nHibernate不喜欢逗号。
将查询更改为
SELECT id, COUNT(id) AS myCount
FROM foo
INNER JOIN bah ON foo.id = bah.fooId
WHERE foo.Name IN (:name)
GROUP BY fooId
运作良好,但没有给我我想要的结果。
有谁知道如何使用任何nHibernate方法实现此结果?
SELECT id, COUNT(id) AS myCount
FROM foo
INNER JOIN bah ON foo.id = bah.fooId
WHERE foo.Name LIKE :name1
OR foo.Name LIKE :name2
OR foo.Name LIKE :name3
GROUP BY fooId
答案 0 :(得分:0)
似乎命名查询不是您的方案的正确选择。相反,您应该动态构建您的查询,如下所示:
var querybase="select f.Id,Count(f.Id) from foo WHERE {0} group by f.Id";
var whereClause=new StringBuilder();
whereClause.Append("0=1 ");
foreach(var name in names)
{
whereClause.Append(string.Format("OR f.Name Like '{0}' ",name));
}
var query=string.Format(querybase,whereClasue);
为了简单起见,我忽略了参数,并将名称值添加到where子句,由于打开SQL注入的位置而不推荐使用,但您可以在此处添加参数名称,然后在查询中设置参数值。
答案 1 :(得分:0)
您的原始查询
SELECT id, COUNT(id) AS myCount FROM
foo INNER JOIN bah ON foo.id = bah.fooId
WHERE foo.Name LIKE :name1
OR foo.Name LIKE :name2
OR foo.Name LIKE :name3
GROUP BY fooId
对于nHibernate
SELECT id, COUNT(id) AS myCount FROM
foo INNER JOIN bah ON foo.id = bah.fooId
WHERE
foo.Name IN (:names)
GROUP BY fooId
理论上,如果
,你的工作应该有效1) you set yours up as a Named Query
2) you have an entity setup as the <return class="">
3) you use SetParameterList
4) names is a string array or ArrayList
例如你的hbm文件
<sql-query name="MyFooCount" cacheable="false" read-only="true">
<return alias="" class="FooCountEntity" />
<![CDATA[
Your query here...
]]>
</sql-query>
例如您的C#文件
string [] mynames = {"peter", "olivia", "charles"};
query.SetParameterList ("names", mynames);