Java Reference
In-Depth Information
10.3.2. Named queries
Unlike a dynamic query, a named query must be created before it can be used. It's defined
in the entity using annotations or in the XML file defining O/R mapping metadata. A
named query is accessed by its name, thus enabling its use across multiple components
in
an
application.
A
named
query
is
defined
using
the
@javax.persistence.NamedQuery annotation:
@Entity
@NamedQuery(
name = "findAllCategories",
query = "SELECT c FROM Category c WHERE c.categoryName
LIKE :categoryName ")
public class Category implements Serializable {
public List<Category> findAllCategories() {
TypedQuery<Category> query =
entityManager.createNamedQuery("findAllCategories",Category.class);
}
}
For a complex application, you'll probably have multiple named queries. In that case, you
can use the @javax.persistence.NamedQueries annotation to specify multiple
named queries like this:
@Entity
@NamedQueries({
@NamedQuery(
name = "findCategoryByName",
query = "SELECT c FROM Category c WHERE c.categoryName
LIKE :categoryName order by c.categoryId"
),
@NamedQuery(
name = "findCategoryByUser",
query = "SELECT c FROM Category c JOIN c.user u
WHERE u.userId = ?1"
)})
@Table(name = "CATEGORIES")
public class Category implements Serializable {
...
}
Search WWH ::




Custom Search