A new colleague has just suggested using named HQL queries in Hibernate with annotations (i.e. @NamedQuery) instead of embedding HQL in our XxxxRepository classes.
What I'd like to know is whether using the annotation provides any advantage except for centralising queries?
In particular, is there some performances gain, for instance because the query is only parsed once when the class is loaded rather than every time the Repository method is executed?
Named queries are compiled when SessionFactory is instantiated (so, essentially, when your application starts up). The obvious advantage, therefore, is that all your named queries are validated at that time rather than failing upon execution.
Hibernate Named Query can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery .
You can define a named query using a @NamedQuery annotation on an entity class or using a <named-query /> element in your XML mapping.
A named query is a static HQL or SQL query with a fixed query string and defined either using @NamedQuery annotation or an XML file. We can refer to a named query by its name, in the runtime, when we need to execute it.
from Pro EJB 3 (Mike Keith):
"...we recommend named queries whenever possible. Persistence providers will often take steps to precompile JPQL named queries to SQL as part of the deployment or initialization phase of an application."
Although this book is on JPA, the general advice applies to Hibernate. However, since Hibernate caches parsed HQL/JPQL, you probably won't see a big performance gain. Another advantage of using named queries is that it gives you the option to override a query using a mapping file at deployment time without having to rebuild your application; useful if you need to tweak a query in production.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With