Tuesday, August 9, 2011

Named Queries in Hibernate

After a code review, somebody asked me about the difference between Named Queries and write your own HQL in your methods (embedding HQL in our DAO's)
Interesting topic!

IMHO, I say that both scenarios are perfectly correct, but...
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.
One 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.
And for me the main advantage is that Hibernate parses the queries at startup so any errors will be detected promptly (This one is the most important advantage for me)

No comments:

Post a Comment