6

Possible Duplicate:
How do we count rows using Hibernate?

I want count number of records by criteria in database.
I try use next query

String queryString = "SELECT Count(*) FROM my_table";  
Query query = entityManager.createNativeQuery(queryString);  

but there is no method to execute this Query query and get result.
I know, that I can count records using

String queryString = "SELECT * FROM my_table";  
Query query = entityManager.createNativeQuery(queryString); 
query.getResultList().size();  

so question, is query with Count(*) more performance, and if yes, then how can I execute query with Count(*)?

Community
  • 1
  • 1
Ilya
  • 29,135
  • 19
  • 110
  • 158

2 Answers2

10

You can execute your first query by calling Query.getSingleResult(), eg.

String queryString = "SELECT Count(*) FROM my_table";  
Query query = entityManager.createNativeQuery(queryString); 
System.out.println(query.getSingleResult());

If you want to assign the count to a variable you need to cast it to proper type (it can depend on DB but most likely it's Long). The second query is very inefficient because Hibernate needs to retrieve entire table from DB, analyze it and then count all rows.

Adam Dyga
  • 8,666
  • 4
  • 27
  • 35
2

Have you tried calling query.getSingleResult()?

RobertG
  • 1,550
  • 1
  • 23
  • 42