A named query in JPA, as the name suggest, is a query you define and associate with your entities, which are given unique names, that can be used later to create the query without re-specifying its syntax. This way, you can remove the same query multiple times, without having to write it again.
To define a named query, we will annotate our entity with the @NamedQuery
annotation, specifying the name and the query itself, as shown in the following example:
@Entity @NamedQuery(name = "fetchAllMovies", query = "SELECT m FROM Movie m") public class Movie { .... }
Then, in order to use this query, we will use the createNamedQuery
method, passing the name of our query, as shown in the following example:
Query q = entityManager.createNamedQuery("fetchAllMovies"); List<Movie> movies = q.getResultList();
Of course, we can specify queries with named parameters, as shown in the following example:
@Entity @NamedQuery(name = "fetchMovie", query = "SELECT m FROM Movie m WHERE m.id...