Ilkar
Ilkar

Reputation: 2177

count hibernate and Named Query

I want to count elements from table using NamedQueries.

NamedQuery is:

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

and:

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

In model I use:

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

How to get count value from query?

Upvotes: 1

Views: 4735

Answers (2)

Sireesh Yarlagadda
Sireesh Yarlagadda

Reputation: 13736

You can even try this, if you are hibernate version < 4

int count = ((Number)em.createNamedQuery("Advertisement.countBySubcategoryList").getSingleResult()).intValue();

if you are hibernate version >= 4 . @Maric is right

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

Upvotes: 1

Predrag Maric
Predrag Maric

Reputation: 24433

Your query should be something like

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

And you should call it like this

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

EDIT

Hibernate versions prior to 4 returned Integer instead of Long for this type of query.

Upvotes: 5

Related Questions