Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate native query, count [duplicate]

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(*)?

like image 258
Ilya Avatar asked Oct 24 '12 12:10

Ilya


1 Answers

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.

like image 75
Adam Dyga Avatar answered Sep 19 '22 00:09

Adam Dyga