简体   繁体   中英

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?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM