Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 49 enterprise java below However this would increase the potential for runtime errors because the field name would not be checked during compilation Using a string based field name Not the preferred approach Predicate condition cb equal from get shape RECTANGLE After obtaining the Predicate the CriteriaQuery can then be altered by initiating a call to the where method passing the Predicate The where method acts as a modifier to the initial CriteriaQuery object allowing the query to be altered to set one or more conditions The CriteriaQuery also contains a number of other modifiers See the JavaDoc for more details cq where condition Lastly obtain the TypedQuery object by calling upon the EntityManagers createQuery method and passing the CriteriaQuery object Finally obtain the ResultList from the TypedQuery Listing 4 shows the complete example code Listing 4 CriteriaBuilder cb em getCriteriaBuilder CriteriaQuery cq cb createQuery Root Pool from cq from Pool class Predicate condition cb equal from get Pool_ shape RECTANGLE cq where condition TypedQuery Pool typedQuery em createQuery cq return typedQuery getResultList In the case where there is more than one condition that needs to be applied to your query simply create a new Predicate and then pass to the CriteriaQuery where method each of the Predicate objects separated by commas Listing 5 demonstrates a query that returns all ROUND pools that can hold more than 25000 gallons of water This particular listing certainly shows the benefits of the strongly typed Criteria API Listing 5 CriteriaBuilder cb em getCriteriaBuilder CriteriaQuery cq cb createQuery Root Pool from cq from Pool class Predicate condition1 cb equal from get Pool_ shape ROUND Predicate condition2 cb gt from get Pool_ gallons 25000 cq where condition1 condition2 TypedQuery Pool typedQuery em createQuery cq return typedQuery getResultList For instance if you were to pass a String to the Criteria Builder gt method the compilation will fail because it expects a numeric value It is easy to reconstruct this CriteriaQuery to make it more closely resemble SQL or JPQL syntax if you desire Rather than passing the Predicate conditions and calling upon the EntityManager createQuery separately we would perform these same tasks using a builder pattern to produce a TypedQuery object Moreover we can create a List of Predicates or conditions to make the code more manageable There are other methods that can be invoked within the query builder chain to perform ordering capture distinct fields and so forth Listing 6 demonstrates the same query that we used in Listing 5 but with this streamlined syntax and sorted by the number of gallons Listing 6 CriteriaBuilder cb em getCriteriaBuilder CriteriaQuery cq cb createQuery Root Pool from cq from Pool class List Predicate conditions new ArrayList conditions add
You must have JavaScript enabled to view digital editions.