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(*)
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With