Java Reference
In-Depth Information
In addition to these types of queries, you also have dynamic and named queries. Dynamic
queries are queries created in code—the query is passed off to the EntityManager . A
named query is a query that's either configured in an annotation or pulled from an ORM
XML configuration file. A named query consolidates queries for reuse and keeps them
from becoming buried in code. Let's examine both of these queries in more depth.
Query versus abstract query
We cover several different types of queries in this chapter including JPQL, SQL (native),
and Criteria. javax.persistence.criteria.CriteriaQuery and javax
.persistence.Query don't share a common ancestor despite the apparent similarity
in their names. The two APIs are very different. As you'll see with the Criteria Query API,
you construct queries using Java objects and not free-form strings that are interpreted at
runtime.
10.3.1. Dynamic queries
Dynamic queries are created on the fly and embedded within the code. Dynamic queries are
typically only used once—that is, the query isn't shared among multiple components in an
application. If you're already using JDBC ( Statements or PreparedStatements ),
this approach will look very familiar. Dynamic queries can contain either JPQL or native
SQL. A simple example is as follows:
@PersistenceContext
private EntityManager entityManager;
public List<Category> findAllCategories() {
TypedQuery<Category> query = entityManager.createQuery(
"SELECT c FROM Category c",Category.class);
return query.getResultList();
}
In this example the EntityManager provided by dependency injection is used. Then an
instance of a TypedQuery is created , which leverages Java's Generics so that you don't
have to cast the results. Once you have the query, the final step is to invoke getRes-
ultList() to execute and retrieve the results of the query. You can also use dynam-
ic queries to execute both native SQL and stored procedure queries as well—with cre-
ateNativeQuery and createStoredProcedureQuery , respectively.
Search WWH ::




Custom Search