Java Reference
In-Depth Information
Named Queries (HQL or EJB QL)
@NamedQuery and @NamedQueries allow one or more EJB QL queries to be associated with an
entity. The required attributes are as follows:
name is the name by which the query is retrieved.
query is the EJB QL (or HQL) query associated with the name.
Listing 6-29 shows an example associating a named query with the Author entity. The
query would retrieve Author entities by name, so it is natural to associate it with that entity—
however, there is no actual requirement that a named query be associated in this way with the
entity that it concerns.
Listing 6-29. An EJB QL Named Query Annotation
@Entity
@NamedQuery(
name="findAuthorsByName",
query="from Author where name = :author"
)
public class Author {
...
}
There is also a hints attribute, taking a QueryHint annotation name/value pair, which
allows caching mode, timeout value, and a variety of other platform-specific tweaks to be
applied (this can also be used to comment the SQL generated by the query).
You do not need to directly associate the query with the entity against which it is declared,
but it is normal to do so. If a query has no natural association with any of the entity declara-
tions, it is possible to make the @NamedQuery annotation at the package level.
There is no natural place to put a package-level annotation, so Java annotations allow for
a specific file, called package-info.java , to contain them. Listing 6-30 gives an example of this.
Listing 6-30. A package-info.java File
@javax.annotations.NamedQuery(
name="findAuthorsByName",
query="from Author where name = :author"
)
package com.hibernatebook.annotations;
Hibernate's session allows named queries to be accessed directly, as shown in Listing 6-31.
Listing 6-31. Invoking a Named Query via the Session
Query query = session.getNamedQuery("findAuthorsByName") ;
query.setParameter("author", "Dave");
List booksByDave = query.list();
System.out.println("There is/are " + booksByDave.size()
+ " author(s) called Dave in the catalog");
Search WWH ::




Custom Search