The Criteria API provides a way of creating type-safe queries. Its type-safe quality is the result of the Java compiler's ability to perform syntax checking at compile-time and the run-time environment's ability to catch and handle exceptions. Using this API can result in more robust and stable applications.
The Criteria API is a complex API. Complete coverage is not possible here. The intent is to provide an introduction to its use.
There are two basic approaches for using the Criteria API. The first is through the use of strongly-typed queries based on the use of java.persistence.metamodel
interfaces. This is a more complex approach requiring the use of metamodel objects for the management of the queries. A second approach uses strings but is not as type safe. It is this latter approach that we will demonstrate here.
Add a method called findAllMales
to the PatientFacade
class. The method is passed a PrintWriter
object and returns void. Within the method, Criteria API classes are used to return a list of male patients and then the list is displayed.
public void findAllMales(PrintWriter out) { CriteriaBuilder criteriaBuilder; criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Patient> criteriaQuery = criteriaBuilder.createQuery(Patient.class); Root<Patient> patientRoot = criteriaQuery.from(Patient.class); criteriaQuery.where(criteriaBuilder.equal( patientRoot.get("sex"),"M")); List<Patient> patients = getEntityManager().createQuery(criteriaQuery).getResultList(); for (Patient p : patients) { out.println("<h5>" + p.getFirstName() + "</h5>"); }
Modify the Patient
Servlet and add a call to the findAllMales
method after the display of the body tag.
... out.println("<body>"); patientFacade.findAllMales(out);
Execute the PatientServlet
and you should get a list of male patients as shown in the following screenshot:
An instance of the CriteriaBuilder
was created using the EntityManager
class's getCriteriaBuilder
method. Next, an instance of a CriteriaQuery
was created based on the Patient
class. This instance represents a query. A Root
instance was created using the from
method. This root referenced the Patient
entity.
The where
method was executed against the CriteriaQuery
object to restrict the query results to those specified by its argument. This argument was a Predicate
object returned by the equal
method. The argument of this method restricted matches to those where the patient was a male. The get method used an argument of sex
which was compared to the"M"
string to determine if the patient was male.
A List
of patients was then returned using the getResultList
method executed against the CriteriaQuery
object. The list was then displayed.
3.14.131.212