40

I want to execute the below query in Hibernate?

select count(*) from login where emailid='something' and password='something'

xrcwrn
  • 5,339
  • 17
  • 68
  • 129
user2510115
  • 674
  • 2
  • 8
  • 17
  • Um... how about `select count(*) from Login login where login.emailid='something' and login.password='something'`? Or are you asking how to execute a HQL query at all? – Joachim Isaksson Jun 29 '13 at 19:08

3 Answers3

94

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.

eternay
  • 3,754
  • 2
  • 29
  • 27
  • 1
    On using it the same way, I am getting an error, table or view does not exist. The query with the tablename, is working fine in db. Any idea what the error is? – Aparna Aug 16 '16 at 07:03
  • Works fine with Hibernate 5.3.1. – BobC Jul 06 '19 at 02:04
  • I had to use getSingleResult() instead uniqueResult(). The latter was not available – Davide Nov 13 '20 at 10:07
  • 1
    If anyone like me faced the error of _BigDecimal cannot cast it to Long_ when trying to use the solution above, use this: `Long count = ((BigDecimal) query.uniqueResult()).longValue();` – Houari Zegai Dec 28 '20 at 08:49
  • This query is not valid HQL and my no longer work if Hibernate will become more strict. It should be select count(login) from LoginClass login – Simon Martinelli Mar 24 '21 at 13:03
1

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();
borchvm
  • 3,533
  • 16
  • 44
  • 45
0

You can query in Hibernate 6 this way:

public int getCount() {
    int result = 0;
    try {
        session.beginTransaction();

        result = session.createNativeQuery("select count(*) from user", Integer.class).uniqueResult();

        session.getTransaction().commit();

    } catch (Exception exception) {
        exception.printStackTrace();
    }

    return result;
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36