I want to exploit the db independent HQL and Type safety of Criteria API. But I don't have entity classes.
Can I use Criteria API directly?
I want to exploit the db independent HQL and Type safety of Criteria API. But I don't have entity classes.
Can I use Criteria API directly?
No, you can't. The point of HQL and Criteria API is to query an object model, based on entities and associations between them.
First it's good to notice the Criteria API is commonly used as substitute of HQL for building dynamic queries ("HQL is extremely powerful, but some developers prefer to build queries dynamically using an object-oriented API, rather than building query strings" reference link).
Second, Hibernate is an Object/Relation(Database) persistence implementation. In order to use it we need to define the classes whose Objects shall be mapped into the targeted Database Tables(Entities).
For the Criteria API is obtained for an Hibernate Session using an Domain Class:
Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(50);
List cats = crit.list();
the Session object uses the mapping from the "Cat" class to its corresponding Table (probably named "Cat" in the Database).
So, finally without entities classes and their Mappings, no Session object . And no Session , no Criteria object.
Criteria needs to know the Classes (Cat.class) that need to be queried.
how can you tell hibernate that which class you want to applied critera??
So you have to pass entity class name in createcriteria(Entity.class).
And ya... Criteria provides rich functionality, which will reduce your code.
But mind that... all things have positive - negative point.
Criteria has also some negative point...
So.. Be careful. Use as per your application related specification