Using JPA2.0 (via Hibernate 4), I can query the database for a record where the query criteria is the primary key by using EntityManager.find(java.lang.Class entityClass, java.lang.Object primaryKey). But if the query criteria isn’t a primary key (for example, select all records whose city value is ‘london’), do I have to create a TypedQuery and explicitly provide the SQL statement? Is there any best practice I should adopt?
Share
The JPA Criteria API provides you with a level of compile-time safety you won’t get with constructing your own dynamic queries (using jpql or sql). Especially when a lot of conditions start to creep in (optional fields, conditional subqueries, …) it can become very easy to make mistakes.
The Criteria API can be more complex to write (especially for simple queries), and you need to create some plumbing code around the criteria API to make it a truly dynamic and easy to use language. It doesn’t really offer it out of the box.
Some people like working with the Criteria API, while others prefer named queries / JPQL.