How to write a query in hibernate for count(*)

Suppose your login table is mapped by a LoginClass class, with emailid and password instance variables. Then you'll execute something like:

Query query = session.createQuery(
        "select count(*) from LoginClass login where login.emailid=:email and login.password=:password");
query.setString("email", "something");
query.setString("password", "password");
Long count = (Long)query.uniqueResult();

It should return in count the result you're looking for. You just have to adapt the name to your class and your parameter names.


The result returns BigDecimal and you need to convert it from Bigdecimal (java.math.BigDecimal) to Long so that no error, he solution would be this:

Query query = session.createSQLQuery(
        "select count(*) from login where login.emailid=:email and login.password=:password");
query.setString("email", "something");
query.setString("password", "password");
Long count = ((BigDecimal) query.uniqueResult()).longValue();

Tags:

Hibernate

Hql