Junior — Middle
Have you used named queries in Hibernate in your practice?
sobes.tech AI
Answer from AI
Yes, in practice with Hibernate, named queries are often used. These are predefined queries that can be reused in code by name. They are declared in annotations or XML configurations and help improve code readability and maintainability, as well as being optimizable by the JPA provider.
Example of declaring a named query with an annotation:
@Entity
@NamedQuery(
name = "User.findByEmail",
query = "FROM User u WHERE u.email = :email"
)
public class User {
// fields and methods
}
// Usage:
TypedQuery<User> query = entityManager.createNamedQuery("User.findByEmail", User.class);
query.setParameter("email", "example@example.com");
User user = query.getSingleResult();