views:

354

answers:

2

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 quueries?

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?

+5  A: 

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.

Ken Liu
+3  A: 

Apart from any possible performance gain, I believe another advantage would be that by using HQL queries with annotations you can protect yourself from SQL Injection attacks.

For a web application, this is important if the query contains any user input data.

http://en.wikipedia.org/wiki/SQL_injection

Lars Andren