Databases Reference
In-Depth Information
The Criteria API
The Criteria API was introduced to address the problems found while using JPQL
and to standardize the criteria efforts of third party ORM frameworks. It is used to
construct query definition objects, which are transformed to the executed SQL query.
The next code example demonstrates that we can implement our query by using the
Criteria API:
//Obtain an instance of entity manager
EntityManager em = …
//Get criteria builder
CriteriaBuilder cb = em.getCriteriaBuilder();
//Create criteria query
CriteriaQuery<Contact> query = cb.greateQuery(Contact.class);
//Create query root
Root<Contact> root = query.from(Contact.class);
//Create condition for the first name by using static meta
//model. You can also use "firstName" here.
Predicate firstNameIs = cb.equal(root.get(Contact_.firstName, "John");
//Specify the where condition of query
query.where(firstNameIs);
//Create typed query and get results
TypedQuery<Contact> q = em.createQuery(query);
List<Contact> contacts = q.getResultList();
We can see three things from this example:
• The created query is type safe and results can be obtained without casting
• The code is not as readable as the corresponding code that uses SQL or JPQL
• Since we are dealing with a Java API, the Java compiler ensures that it is not
possible to create syntactically incorrect queries
 
Search WWH ::




Custom Search