Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

What are JPA named queries (@NamedQuery), when are they validated, and how does Spring Data JPA pick them up for a repository method?

A named query is a JPQL query defined once under a name, usually with @NamedQuery on an entity, such as @NamedQuery(name = "Order.findOpen", query = "select o from Order o where o.status = 'OPEN'"). Hibernate parses and validates named queries at startup, so a syntax error stops the application. Spring Data uses it for a repository method whose name matches DomainType.methodName, before it tries to derive a query from the method name, and plain JPA runs it with entityManager.createNamedQuery("Order.findOpen", Order.class).

Why this question is asked

Named queries are one of the oldest features of JPA and still show up in many codebases, especially ones that started before Spring Data was common. Interviewers ask about them to see whether we understand the lookup rules Spring Data follows, because those rules explain surprises such as a repository method running a query nobody can find next to it. In this answer, we will define a named query, see when it is validated, run it from plain JPA, follow how Spring Data picks it up, and compare it with @Query.

1Defining a Named Query

A named query is attached to an entity class, or to any class JPA scans, with @NamedQuery. It has a name, which must be unique in the persistence unit, and a JPQL string. By convention the name starts with the entity name and a dot, which also happens to be the convention Spring Data relies on.

Java
@Entity
@Table(name = "orders")
@NamedQuery(name = "Order.findOpen",
query = "select o from Order o where o.status = 'OPEN' order by o.createdAt desc")
@NamedQuery(name = "Order.findByCustomer",
query = "select o from Order o where o.customer.id = :customerId")
public class Order {
@Id Long id;
String status;
Instant createdAt;
@ManyToOne Customer customer;
}

Since JPA 2.2 @NamedQuery is repeatable, so we can stack several on one class as above; older code wraps them in @NamedQueries. The same queries can also live in META-INF/orm.xml as named-query elements, which keeps them out of the entity class.

2When Named Queries Are Validated

When the persistence unit starts, Hibernate reads every named query, parses it, and checks it against the entity model: does the entity exist, does it have a field called status, do the types make sense? If anything is wrong, startup fails with an error naming the query.

Java
@NamedQuery(name = "Order.findOpen",
query = "select o from Order o where o.stauts = 'OPEN'") // typo
// At startup:
// org.hibernate.HibernateException: Errors in named queries: Order.findOpen
// (the exact exception and message depend on your Hibernate version)

This is the main historical advantage of named queries: errors surface when the application starts, in every environment including tests, rather than the first time a user hits the code path. A JPQL string built inline with createQuery is only parsed when that line runs.

3Running a Named Query From Plain JPA

With the EntityManager we refer to the query by its name and get a typed query back, then bind parameters and execute as usual.

Java
List<Order> open = em.createNamedQuery("Order.findOpen", Order.class)
.setMaxResults(50)
.getResultList(); // the 50 newest open orders
List<Order> mine = em.createNamedQuery("Order.findByCustomer", Order.class)
.setParameter("customerId", 42L)
.getResultList(); // orders of customer 42

Notice that the query string is not visible here. That is the trade-off of named queries: the code that runs the query and the query itself live in different files.

4How Spring Data Picks Up a Named Query

Spring Data JPA decides what to run for each repository method using a lookup strategy. The default, CREATE_IF_NOT_FOUND, tries three things in order. First, a @Query annotation on the method. Second, a named query called DomainType.methodName, where DomainType is the simple name of the repository's entity type. Third, if neither exists, it derives a query from the method name.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findOpen(); // runs named query "Order.findOpen"
List<Order> findByCustomer(@Param("customerId") Long id); // runs "Order.findByCustomer"
List<Order> findByStatus(String status); // no named query: derived from the name
}
Step throughHow Spring Data chooses the query for a method
  1. Does the method have @Query?
    YesUse the @Query stringNoLook for a named query
  2. Is there a named query Order.methodName?
    YesUse the named queryNoDerive from the method name
  3. Validate at startupJPQL from all three paths is checked when the repository is created

3 steps in order. Play them, or step through them one at a time.

So findOpen() works even though open is not a property, because Spring Data finds Order.findOpen before it tries to derive anything. Notice the second method: the named query uses the named parameter :customerId, so the method parameter needs @Param with that name, or the code must be compiled with parameter names. The flip side of this convenience is surprise: a developer renaming findOpen() to findOpenOrders() silently switches it to derivation, which then fails at startup because there is no openOrders property.

5Named Queries Versus @Query Today

In modern Spring Data code, @Query on the repository method is the more common choice. It keeps the query next to the method that runs it, so readers see both at once, and the entity class stays focused on mapping. Spring Data also validates JPQL @Query strings at startup, by creating the query when the repository is initialized, so the fail-fast advantage that once favoured named queries applies to both.

Named queries still have uses: sharing one query between several repositories or plain JPA code, keeping queries in orm.xml so they can be changed without touching annotated classes, and existing codebases where moving them would add risk without benefit.

6Follow-up questions

What happens if two named queries have the same name?

Names must be unique in the persistence unit. Depending on the provider and version, a duplicate either fails at startup or one definition silently wins, so never rely on overriding by name. Using the EntityName.purpose convention makes clashes unlikely.

Are native named queries validated the same way?

No. @NamedNativeQuery holds SQL that Hibernate does not parse against the entity model, so a wrong column name is only found when the query runs on the database. Only JPQL named queries get the full startup check.

Can a named query be changed at runtime?

JPA has EntityManagerFactory.addNamedQuery, which registers a query under a name programmatically. It is rarely needed; most applications define their queries at startup and treat them as fixed.

7Conclusion

In this answer, we saw that a named query is a JPQL query registered under a name with @NamedQuery or in orm.xml, that Hibernate parses and validates it at startup so errors fail fast, and that plain JPA runs it with createNamedQuery. Spring Data uses a named query called DomainType.methodName when the method has no @Query and before deriving from the name. Today @Query on the method is more common because it keeps the query next to its method and is validated at startup too.

What to say in the interviewAbout 80 seconds aloud

Open with

A named query is a JPQL query defined once under a name, typically with @NamedQuery on the entity, like name Order.findOpen with select o from Order o where o.status is OPEN.

Then, if they want more

Hibernate parses and validates all named queries when the persistence unit starts, so a typo in a field name stops the application at startup instead of failing later in production. From plain JPA I run it with entityManager.createNamedQuery("Order.findOpen", Order.class) and bind parameters as usual. Spring Data picks it up by naming convention.

For each repository method its default lookup strategy first looks for @Query, then for a named query called the entity's simple name, a dot, and the method name, so findOpen on an Order repository runs Order.findOpen, and only if neither exists does it derive the query from the method name.

That is also a trap: renaming the method silently switches it to derivation. Nowadays I mostly use @Query on the repository method, because the query sits next to the code that runs it, and Spring Data validates JPQL @Query at startup as well. Named queries still make sense when a query is shared or kept in orm.xml.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What are JPA named queries (@NamedQuery), when are they validated, and how does Spring...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/fc0103e11d/