A criteria query constructs a JPA query programmatically. Selections and restrictions use the Criteria API instead of query-language strings, enabling dynamic query construction and, with the static metamodel, compile-time attribute checks. section 1.3 section 3.3.4
Filtering items by name
CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Item> query = cb.createQuery(Item.class); Root<Item> item = query.from(Item.class); query.select(item); query.where(cb.like(item.get(Item_.name), cb.parameter(String.class, "pattern"))); List<Item> items = em.createQuery(query) .setParameter("pattern", "%Item 1%") .getResultList(); The query represents a select from Item with a like restriction on name. Using item.get("name") leaves the attribute lookup string-based; using Item_.name uses generated static metamodel metadata. section 3.3.4
A criteria query typically involves these elements:
- Obtain a CriteriaBuilder from the EntityManager. section 3.3.4
- Create a typed CriteriaQuery, declare an entity Root, and select it. section 3.3.4
- Add predicates such as like expressions and bind parameters before executing through the EntityManager. section 3.3.4
- Use generated metamodel classes such as Item_ to detect renamed or mismatched attributes during compilation rather than at runtime. section 3.3.4
Path: Ch03/metamodel/src/test/java/com/manning/javapersistence/ch03 /metamodel/MetamodelTest.java CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Item> query = cb.createQuery(Item.class); #1 Root<Item> fromItem = query.from(Item.class); query.select(fromItem); List<Item> items = em.createQuery(query).getResultList(); assertEquals(2, items.size()); #1 The query is the equivalent of <kbd>select i from Item i</kbd>. This query returns all items in the database, and there are two in this case. If you want to restrict this result and only return items with a particular name, you will have to use a <kbd>like</kbd> expression, comparing the <kbd>name</kbd> attribute of each item with the pattern set in a parameter.
Shows the minimal Criteria API construction for selecting every Item before adding restrictions. section 3.3.4
