Cover by Dan Sanderson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Queries and JPQL

JPA includes a SQL-like query language called JPQL. JPQL provides access to the underlying database’s query functionality at the level of abstraction of JPA data objects. You form queries for data objects in terms of the data classes, and get objects as results.

To perform a query, you call the entity manager’s createQuery() method with the text of the JPQL query. This returns a Query object. To get the results, you call getResultList() on the Query object.

import java.util.List;
import javax.persistence.Query;

// ...

    Query query = em.createQuery("SELECT b FROM Book b");

    @SuppressWarnings("unchecked")
    List<Book> results = (List<Book>) query.getResultList();

In this example, the cast to List<Book> generates a compiler warning, so we suppress this warning using an @SuppressWarnings annotation.

JPA knows which class to use for each result from the @Entity(name = "...") annotation on the class. You can also use the full package path of the class in the query.

You can use parameters in your JPQL query, and replace the parameters with values by calling setParameter():

    Query query = em.createQuery(
        "SELECT b FROM Book b WHERE copyrightYear >= :earliestYear");
    query.setParameter("earliestYear", 1923);

getResultList() returns a special App Engine–specific implementation of List that knows how to fetch results in batches. If you iterate over the entire list, the List implementation may make multiple calls to the datastore to fetch results.

If you are only expecting one result, you ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required