I use HQL queries in Hibernate, and just wondered, if I could increase the preformance of my app reusing queries.
Usually you have to create a new Query object for each session:
Session session;
Query q1 = session.createQuery("select a from Article a where id=:id");
q1.setInteger("id",123);
List result = q1.list();
Now I have relatively complex queries in HQL, which I don't want to have parsed over and over again. Is there a way to create a query and reuse itt in another session? Like this:
Session session;
Query q2 = q1.reattach();
q2.setInteger("id",123);
List result = q2.list();
If Hibernate uses prepared statements anyway, this should be a notable performance gain, especially in combination with a ConnectionPool that caches prepared statements.
EDIT: Reusing Queries in Hibernate is usually not needed, because the query plan is already cached in the class QueryPlanCache anyway. Named Queries also do not provide any improvement also, because they are just used to lookup the query string and no plan is associated with them.
To conclude: There is no use in reusing Queries in Hibernate. Just be sure to use parametrized queries ALWAYS, so keep the plan caches small.
To create query in the Hibernate ORM framework, there is three different types.
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.
You may use 'Named Query': Annotate your Entity class like
@Entity
@NamedQuery(name="Article.findById", query="select a from Article a where id=:id")
public class Article{ ...
and then it will be parsed once at start up, whenever you want using it you simply call:
session.getNamedQuery("Article.findById")
.setInteger("id",123);
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