Home/Learn/Hibernate & JPA/Named Queries

Named Queries

Intermediate
Querying

@NamedQuery precompiles JPQL at startup, enabling early syntax validation and potential query plan caching; defined on the entity class for discoverability.

Overview

@NamedQuery defines a static, named JPQL query on an entity class. All @NamedQuery annotations are parsed and validated at application startup — a syntax error fails fast rather than at runtime. Hibernate also generates and caches the SQL translation, so there is no re-parsing cost per call. Named queries are typically invoked via EntityManager.createNamedQuery() or Spring Data's @Query(name=) attribute. @NamedNativeQuery is the equivalent for raw SQL. With Spring Data JPA, method-name derived queries and @Query annotations have largely replaced @NamedQuery for greenfield code, but @NamedQuery remains useful for complex queries that belong conceptually to the entity.

Defining @NamedQuery

Place @NamedQuery (or @NamedQueries for multiple) directly on the entity class. The name conventionally follows the pattern EntityName.queryDescription.

Java — @NamedQuery definition on entity
@Entity
@Table(name = "orders")
@NamedQueries({
    @NamedQuery(
        name  = "Order.findByCustomer",
        query = "SELECT o FROM Order o WHERE o.customerId = :customerId ORDER BY o.createdAt DESC"
    ),
    @NamedQuery(
        name  = "Order.countPendingByCustomer",
        query = "SELECT COUNT(o) FROM Order o WHERE o.customerId = :customerId AND o.status = 'PENDING'"
    )
})
public class Order {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long customerId;
    private String status;
    private LocalDateTime createdAt;
}

Executing Named Queries

In plain JPA, use EntityManager.createNamedQuery(). In Spring Data JPA, reference the named query by name using the @Query annotation or by following the repository method naming convention EntityName.methodName.

Java — executing @NamedQuery via EntityManager and Spring Data
// Plain JPA
List<Order> orders = em.createNamedQuery("Order.findByCustomer", Order.class)
    .setParameter("customerId", customerId)
    .setMaxResults(20)
    .getResultList();

// Spring Data — method name matches NamedQuery automatically
// Interface method name: findByCustomer(Long customerId)
// Spring Data looks for a NamedQuery "Order.findByCustomer" first
public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByCustomer(Long customerId);       // matches Order.findByCustomer
    Long countPendingByCustomer(Long customerId);      // matches Order.countPendingByCustomer
}

@NamedNativeQuery

@NamedNativeQuery defines a raw SQL named query. Specify a @SqlResultSetMapping or resultClass to map rows to an entity or projection.

Java — @NamedNativeQuery with @SqlResultSetMapping
@Entity
@NamedNativeQuery(
    name        = "Order.topOrdersByRevenue",
    query       = """
        SELECT o.id, o.customer_id, SUM(oi.qty * oi.unit_price) AS total
        FROM orders o
        JOIN order_items oi ON oi.order_id = o.id
        GROUP BY o.id, o.customer_id
        ORDER BY total DESC
        LIMIT :limit
        """,
    resultSetMapping = "OrderRevenueSummary"
)
@SqlResultSetMapping(
    name    = "OrderRevenueSummary",
    classes = @ConstructorResult(
        targetClass = OrderRevenue.class,
        columns = {
            @ColumnResult(name = "id",          type = Long.class),
            @ColumnResult(name = "customer_id", type = Long.class),
            @ColumnResult(name = "total",       type = BigDecimal.class)
        }
    )
)
public class Order { ... }

Key Points to Remember

  • 1@NamedQuery JPQL is validated at startup — syntax errors fail fast, not at runtime
  • 2SQL translation is cached per named query — no re-parsing cost per execution
  • 3Convention: name = "EntityName.descriptiveName" for Spring Data auto-detection
  • 4Spring Data looks for a matching @NamedQuery before generating a derived query
  • 5@NamedNativeQuery holds raw SQL; use @SqlResultSetMapping to map results to a DTO
  • 6With Spring Data @Query, explicit inline queries are often clearer than @NamedQuery

Interview Questions

Sign in to ask Aria
1

What is the advantage of @NamedQuery over creating a query in-place?

EasyTCS
2

When does @NamedQuery JPQL get validated?

EasyInfosys
3

How does Spring Data JPA detect and use @NamedQuery definitions?

MediumWipro
4

What is the difference between @NamedQuery and @NamedNativeQuery?

EasyAccenture
5

How would you map a native query result to a DTO?

HardAmazon

Ask Aria about Named Queries

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…