JPA already defines a mechanism for defining
queries, with the @javax.persistence.NamedQuery
and @javax.persistence.NamedQueries annotations.
In theory these can be annotated on any class, but by convention they go
on the class being returned.
For example, we might want to search for
Customers by their id, or by
their surname (family name):
@NamedQueries({
@NamedQuery(name="findCustomerById", query="from Customer where id=:id"),
@NamedQuery(name="findCustomersBySurname", query="from Customer where surname=:surname"),
})
@Entity
@DiscriminatorValue("CUS")
public class Customer {
...
@Id
public Integer getId() { ... }
...
@Basic
public String getFamilyName() { ... }
...
}These named queries are then referenced in the repository implementations, covered next (Section 5.3, “Repository Implementation”).