Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Hibernate named HQL queries (in annotations) optimised?

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?

like image 442
Graham Lea Avatar asked Apr 15 '10 00:04

Graham Lea


People also ask

What is the advantage of named query in hibernate?

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.

Which annotation is correct for named query?

Hibernate Named Query can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery .

Which of the following annotations can be used for providing named queries for an entity class for faster result?

You can define a named query using a @NamedQuery annotation on an entity class or using a <named-query /> element in your XML mapping.

Which method is used to call named SQL query in hibernate?

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.


1 Answers

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.

like image 145
Ken Liu Avatar answered Sep 28 '22 08:09

Ken Liu