Sobes.tech
Middle

What is a Named Query in Hibernate?

sobes.tech AI

Answer from AI

A named query in Hibernate is a predefined SQL or HQL query associated with a unique name. It is defined using the @NamedQuery annotation or in the orm.xml file. This allows managing queries in one place, improving readability and ease of maintenance.

Advantages:

  • Readability: Queries are centralized, making the code more understandable.
  • Reusability: The query can be invoked by name from different parts of the application.
  • Startup validation: Hibernate checks the syntax of HQL/JPQL named queries when loading the context, which helps identify errors before execution.
  • Refactoring convenience: When changing a query, it only needs to be edited in one place.

Example with @NamedQuery annotation:

// in the entity class

@Entity
@NamedQuery(name = "findAllPersistedClasses", query = "SELECT p FROM PersistedClass p")
public class PersistedClass {
    @Id
    private Long id;
    private String name;

    // getters and setters
}
// usage in code

Session session = sessionFactory.openSession();
Query query = session.createNamedQuery("findAllPersistedClasses", PersistedClass.class);
List<PersistedClass> resultList = query.getResultList();
session.close();

Example with orm.xml file:

<!-- orm.xml -->

<entity-mappings
        xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_2.xsd"
        version="2.2">
    <named-query name="findAllPersistedClassesXml">
        <query>SELECT p FROM PersistedClass p</query>
    </named-query>
</entity-mappings>
// usage in code

Session session = sessionFactory.openSession();
Query query = session.createNamedQuery("findAllPersistedClassesXml", PersistedClass.class);
List<PersistedClass> resultList = query.getResultList();
session.close();