12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 4 ■ MANAGING PERSISTENT OBJECTSThe previous query retrieves customers named Vincent, but you might want to introduce aparameter for the first name. There are two possible choices for passing a parameter: using names orpositions. In the following example, a named parameter called :fname (note the : symbol) is used in thequery and bound <strong>with</strong> the setParameter method:jpqlQuery = "SELECT c FROM Customer c";if (someCriteria)jpqlQuery += " where c.firstName = :fname";query = em.createQuery(jpqlQuery);query.setParameter("fname", "Vincent");List customers = query.getResultList();Note that the parameter name fname does not include the colon used in the query. The code using aposition parameter would look like the following:jpqlQuery = "SELECT c FROM Customer c";if (someCriteria)jpqlQuery += " where c.firstName = ?1";query = em.createQuery(jpqlQuery);query.setParameter(1, "Vincent");List customers = query.getResultList();If you need to use pagination to display the list of customers by chunks of ten, you can use thesetMaxResults method as follows:TypedQuery query = em.createQuery("SELECT c FROM Customer c", Customer.class);query.setMaxResults(10);List customers = query.getResultList();An issue to consider <strong>with</strong> dynamic queries is the cost of translating the JPQL string into an SQLstatement at runtime. Because the query is dynamically created and cannot be predicted, thepersistence provider has to parse the JPQL string, get the ORM metadata, and generate the equivalentSQL. The performance cost of processing each of these dynamic queries can be an issue, and, if you havestatic queries that are unchangeable, use named queries instead.Named QueriesNamed queries are different from dynamic queries in that they are static and unchangeable. In additionto their static nature, which does not allow the flexibility of a dynamic query, named queries can bemore efficient to execute because the persistence provider can translate the JPQL string to SQL once theapplication starts, rather than every time the query is executed.Named queries are static queries expressed in metadata inside either a @NamedQuery annotation orthe XML equivalent. To define these reusable queries, annotate an entity <strong>with</strong> the @NamedQueryannotation, which takes two elements: the name of the query and its content. So let’s change theCustomer entity and statically define three queries using annotations (see Listing 4-27).155

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!