Kesha Williams highlights the Java Persistence Query Language, or JPQL, the three JPQL use cases that are demonstrated during this course, and the differences between JPQL and SQL.
- [Instructor] Now that you have this amazing inheritance, you're more than likely going to want to retrieve that inheritance so that you can buy something with it, right? Well the act of retrieving persisted entities in Java from the database is called querying. And JPQL allows us to quickly write complex queries which allows us to receive our inheritance. JPQL allows developers to define queries for entities and their persistent state. Let's learn about JPQL, the Java Persistence Query Language that allows developers to define queries for entities and their persistent state.
This query language allows you to write portable queries that work regardless of the underlying datastore. During part one of the course, we saw how using the entity manager API allows us to persist entities using the create method. Once you persist data in the database, there's always a need to retrieve it by querying. We've seen how to query entities using the find method and more specifically the ability to query an entity by ID. That's actually the only way we've seen to retrieve an entity thus far.
Often times just finding an entity by ID is quite limiting as we can only retrieve a single entity using its unique identifier. In practice we often need to retrieve an entity by criteria other than the ID field or we even need to retrieve a list of entities. JPQL has a very rich SQL-like syntax and can be used to create queries that select objects or values based on entity abstract schema types and even on the relationships among them.
For example, JPQL can be used to get a list of bugs by severity, retrieve a list of all tickets, or even determine if a specific application record already exists in the database. JPQL makes writing these queries easy. JPQL takes root in the syntax of SQL. But the main difference is that in SQL, the results obtained are in the form of rows and columns, whereas JPQL returns an entity or a collection of entities.
Keep in mind that the database still uses SQL. Therefore behind the scenes, JPQL uses mapping annotations to transform a JPQL query into SQL. The query is executed on the underlying database with SQL and JDBC calls. And the entity instances are returned to the application. Here's a tip. It is good practice to activate the logging of the SQL statements during development to check the generated SQL statements to ensure they are correct. There you have it.
JPQL allows developers to define queries for entities and their persistent state.
- 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