计算hibernate和Named Query

时间:2015-01-28 14:24:05

标签: java hibernate

我想使用NamedQueries计算表中的元素。

NamedQuery是:

@NamedQuery(name = Advertisement.countBySubcategoryList, query = "select count(*) from  Advertisement where subcategoryId IN (:subcategoryId)")

public static final String countBySubcategoryList = "Advertisement.countBySubcategoryList";

在模型中我使用:

List<Advertisement> advertisements = session.getNamedQuery(Advertisement.countBySubcategoryList)
            .setParameterList("subcategoryId", subcategoryIds)
            .list();

如何从查询中获取计数值?

2 个答案:

答案 0 :(得分:4)

您的查询应该是

select count(a) from Advertisement a where a.subcategoryId IN (:subcategoryId)

你应该这样称呼它

Long count = (Long)session.getNamedQuery(Advertisement.countBySubcategoryList)
            .setParameterList("subcategoryId", subcategoryIds)
            .uniqueResult();

修改

对于此类查询,4之前的Hibernate版本返回Integer而不是Long

答案 1 :(得分:1)

如果你是hibernate版本&lt;你甚至可以试试这个。 4

  

int count =   ((编号)em.createNamedQuery(&#34; Advertisement.countBySubcategoryList&#34;)getSingleResult())的intValue();

如果你是hibernate版本&gt; = 4。 @Maric是对的

  

长计数=   (龙)session.getNamedQuery(Advertisement.countBySubcategoryList)               .setParameterList(&#34; subcategoryId&#34;,subcategoryIds)               .uniqueResult();