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:
-
Saving Courses: The
courseRepository.saveAll(getCourseList())method is used to save a list of courses to the database. -
Building the Criteria Query:
- A
CriteriaBuilderis obtained from theEntityManager. - A
CriteriaQueryfor theCourseclass is created using theCriteriaBuilder. - A
Rootobject is defined to specify the entity from which the query will select data.
- A
-
Defining Predicates:
- A
Predicateis created to filter courses by the category "Spring" using theCriteriaBuilder.equal()method.
- A
-
Executing the Query:
- The
CriteriaQueryis configured with the defined predicate using thewhere()method. - A
TypedQueryis created from theEntityManagerand executed to retrieve the results.
- The
-
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.
FAQ (Frequently asked questions)
What is the Criteria API in JPA?
How does the Criteria API ensure type safety?
What is the benefit of using the Criteria API in terms of error reduction?