Kesha Williams introduces the Criteria API, compares and contrasts JPQL versus the Criteria API, and discusses some advantages of using the Criteria API over JPQL.
- [Instructor] The Criteria API is an alternate method for constructing queries that uses a Java programming language API instead of JPQL or Native SQL. JPA has two main ways of querying the database; JPQL and the Criteria API. As we've seen, JPQL queries are written as simple strings, usually easy to read, but as strings they cannot be checked by a Java compiler. The downsides to JPQL is that if an entity attribute gets renamed, all queries using it break without giving any warning.
The JPA Criteria API seeks to overcome this short coming. The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. There are several advantages to using the Criteria API. First, with the Criteria API, queries are written using Java programming language APIs and are type-safe and portable. Type-safe provides compile time checks, code completion and better refactoring support.
This means errors can be detected earlier during compile time. Portable means that queries work regardless of the underlying data store. Lastly, the Criteria API is nice for building dynamic queries. It is important to note that string-based JPQL queries and JPA criteria-based queries are the same in performance and efficiency. There you have it, the Criteria API is an alternative method for constructing queries in JPA and is used in place of JPQL, providing queries that are type-safe and portable.
- Inheriting entities
- Mapping a superclass
- Querying through JPA
- Defining query parameters
- Creating a compile-time named query
- Using native queries
- Creating stored procedures
- Using the Criteria API
- Refining query results
- Switching between persistence providers