Criteria API

The Criteria API, introduced in JPA 2.0, provides a type-safe way to create queries programmatically. It allows developers to express queries using interfaces and classes that represent various parts of the query, such as the select clause and order-by. This type safety is beneficial as it helps reduce execution-time errors by validating queries at compile time.

Using Criteria API in Practice

In the context of a Spring Boot application, such as the CourseTracker application, most components require no change to utilize the Criteria API. The existing Course class, CourseRepository interface, and other configurations remain unchanged. To demonstrate the use of the Criteria API, a unit test can be defined to illustrate its practical application.

Example: Unit Test with Criteria API

The following listing shows a unit test that demonstrates the use of the Criteria API in the CourseTracker application:

Listing 3.33 Unit test to demonstrate the use of Criteria API

package com.manning.sbip.ch03;
 
// Import Statements are excluded as a matter of readability
 
@SpringBootTest
class CourseTrackerSpringBootApplicationTests {
 
    @Autowired
    private CourseRepository courseRepository;
 
    @Autowired
    private EntityManager entityManager;
    @Test
    public void givenCoursesCreatedWhenLoadCoursesWithQuery
➥ ThenExpectCorrectCourseDetails() {
        courseRepository.saveAll(getCourseList());
 
        CriteriaBuilder criteriaBuilder = 
➥ entityManager.getCriteriaBuilder();
 
        CriteriaQuery<Course> courseCriteriaQuery = 
➥ criteriaBuilder.createQuery(Course.class);
 
        Root<Course> courseRoot = courseCriteriaQuery
➥ .from(Course.class);
 
        Predicate courseCategoryPredicate = 
➥ criteriaBuilder.equal(
➥ courseRoot.get("category"), "Spring");
 
        courseCriteriaQuery.where(courseCategoryPredicate);
 
        TypedQuery<Course> query = 
➥ entityManager.createQuery(courseCriteriaQuery);
        Assertions.assertThat(query.getResultList()
➥ .size()).isEqualTo(3);
 
    }
 
    private List<Course> getCourseList() {
        // Get Courses
    }
}

Explanation of the Test Case

In this test case, the following activities are performed:

  1. Saving Courses: The courseRepository.saveAll(getCourseList()) method is used to save a list of courses to the database.

  2. Building the Criteria Query:

    • A CriteriaBuilder is obtained from the EntityManager.
    • A CriteriaQuery for the Course class is created using the CriteriaBuilder.
    • A Root object is defined to specify the entity from which the query will select data.
  3. Defining Predicates:

    • A Predicate is created to filter courses by the category "Spring" using the CriteriaBuilder.equal() method.
  4. Executing the Query:

    • The CriteriaQuery is configured with the defined predicate using the where() method.
    • A TypedQuery is created from the EntityManager and executed to retrieve the results.
  5. Assertions:

    • The test asserts that the size of the result list is equal to 3, verifying that the query returns the expected number of courses.

This example illustrates how the Criteria API can be used to construct and execute type-safe queries in a Spring Boot application, providing compile-time validation and reducing the risk of runtime errors.