Sobes.tech
Junior — Middle

What is the role and application of named query in the Hibernate framework?

sobes.tech AI

Answer from AI

Named Query in Hibernate is a predefined query with a name that can be reused in code. They are usually declared in @NamedQuery annotations or in mapping XML files.

Main advantages:

  • Reuse of the same query without code duplication.
  • Centralized query management.
  • Ability to check query syntax when loading the session factory.

Example of declaring a Named Query:

@Entity
@NamedQuery(
    name = "User.findByEmail",
    query = "FROM User u WHERE u.email = :email"
)
public class User {
    // fields and methods
}

Usage:

Query query = session.createNamedQuery("User.findByEmail");
query.setParameter("email", "example@mail.com");
User user = (User) query.uniqueResult();

Thus, named queries simplify maintenance and improve code readability when working with queries in Hibernate.