views:

2450

answers:

4

For example, if we have a table Books, how would we count total number of book records with hibernate?

Thanks

+1  A: 

You could try count(*)

Integer count = (Integer) session.CreateQuery("select count(*) from Books").UniqueResult();

Where 'Books' is the name off the class - not the table in the database

Jon Spokes
+1 for answer I agree with.
KLE
Looks suspiciously like .net to me...
skaffman
sorry but its not working with Java and Hibernate :(( I did replace int with Integer, as it is in Java for type casting. )
craftsman
It should work - with Integer instead of int ? You need to put the class name in the HQL, not the table name - is the only thing I can think that may be wrong
Jon Spokes
I believe the post directly below this is more in line with the core Hibernate principles.
mattsidesinger
+7  A: 
return (Number) session.createCriteria("Book").setProjection(Projections.rowCount()).uniqueResult();

It is at least a Number, most likely a Long.

Salandur
A: 

This is what I use:

int countRec = session.createQuery("from City").list().size();

I tried it in about 1000 records and it works just fine.

Milos
in this way you load the entiry table in memory. why don't you use the options given to you by hibernate and the database?
Salandur
A: 

Uhh. And what is in that list? I think there are selected all entities from that table. Do that on table with billions of record an you will see why this is WERY BAD IDEA!

msk