WAS v8.5 > Reference > Developer detailed usage informationCriteria API
The Criteria API is an API for building queries with Java objects, as an alternative to building strings for Java Persistence Query Language (JPQL) queries.
The Criteria API supports building queries dynamically at run time, and also the ability to build type-safe queries that can be verified by the compiler. The correctness of JPQL queries cannot be verified by the compiler, and must be verified at run time during testing.
The following is a sample JPQL query that returns a list of employees with less than five years of service:
SELECT e FROM Employee e WHERE e.serviceyears < 5
Here is a sample of the equivalent Criteria query:QueryBuilder qb = emf.getQueryBuilder(); CriteriaQuery q = qb.create(Employee.class); Root e = q.from(Employee.class); q.where(qb.lt(e.get(Employee_.serviceyears), 5)); TypedQuery tq = em.createQuery(q); List result = q.getResultList();Employee_ is the Metamodel of the Employee class.
Two important features are improvements from JPQL:
- The Criteria API can express queries that are not possible through JPQL. For more detailed information see the section, "Editable data store expressions", in the developerWorks article, Dynamic, typesafe queries in JPA 2.0.
- A CriteriaQuery can be edited programmatically. For more information see the section, "Editable query", in the developerWorks article, Dynamic, typesafe queries in JPA 2.0.
We can read more about the Criteria API in the Apache OpenJPA User Guide.
Subtopics
- Develop JPA 2.x applications for a Java SE environment
Prepare persistence applications to test outside of the application server container in a Java SE environment.- Develop JPA 2.x applications for a Java EE environment
Containers in the application server can provide many of the necessary functions for the JPA in a Java EE environment. The application server also provides JPA command tools to assist you with developing applications in a Java EE environment.
Reference:
Apache OpenJPA User's Guide: JPA Criteria
Related information:
Dynamic, typesafe queries in JPA 2.0