In Hibernate, a named query is a JPQL or SQL expression with a predefined unchangeable query string. You can define a named query either in hibernate mapping file or in an entity class.
Basically, named queries in hibernate is a technique to group the HQL statements in a single location, and lately refer them by some name whenever the need to use them. It helps largely in code cleanup because these HQL statements are no longer scattered in the whole code.
Apart from the above, below are some minor advantages of named queries:
Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an error.
Reusable: They can be accessed and used from several places which increases re-usability.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery.
The following is an example of the definition of a named query in the JPQL/HQL:
@NamedQuery(
name="findAllCustomersWithName",
query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
Hibernate provides support to create named queries using Native SQL. Here are @NamedNativeQuery and @NamedNativeQueries annotations to create a named SQL queries.