Chapter 10. Using the query API and JPQL to retrieve entities
This chapter covers
- Creating and executing queries
- The Java Persistence Query Language
- Using SQL queries
Chapters 8 and 9 discussed how the EJB 3 Java Persistence API (JPA) O/R mapping mechanism shields developers from having to write SQL to directly manipulate data. Chapter 8 explained how to map entities to relational tables, and chapter 9 revealed how to manipulate those entities using the EntityManager API. The next couple of topics we’ll tackle in our quest for JPA mastery are the query API and the Java Persistence Query Language (JPQL). We’ll continue to use ActionBazaar to explore these new concepts, incorporating JPQL into our auction system as well as looking at how the various one-to-many and many-to-one mappings work with JPA.
With JPA, you can use the following methods to retrieve entities and related data:
- EntityManager.find with the entity’s primary key
- Queries written in JPQL
- SQL queries native to the underlying database
We discussed the first option, retrieving entities using a primary key, in chapter 9. In this chapter we’ll focus on retrieving entities using the latter two methods: JPQL and SQL queries. First we’ll look at the query API and show you how to execute queries; then we’ll explore the basics of JPQL. The chapter concludes by exploring the use of SQL queries with EJB 3.