To this point, all queries have been defined dynamically by supplying a string containing the query to the EntityManager.createQuery()
method. A named query is an alternative with improved run time performance of the query. A named query is predefined using the @NamedQuery
annotation in the class definition of any entity. The @NamedQuery
annotation takes two arguments: the name of the query and the query text itself.
For example, we can insert the following named query in the Customer class definition:
@NamedQuery(name="findSelectedCustomers", query = "SELECT c FROM Customer c " + "WHERE c.firstName LIKE :firstString " + " AND c.lastName LIKE :secondString")
This query could be placed in any class definition, but as it relates to customers it makes sense to place it in the Customers class definition. The scope of a named query is the current persistence context, so query names are unique with respect to the current persistence context. For example, you cannot have a findCustomersAndAccounts...