Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing Queries in Hibernate

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.

like image 848
Daniel Avatar asked Apr 03 '11 09:04

Daniel


People also ask

How many types of queries are there in hibernate?

To create query in the Hibernate ORM framework, there is three different types.

Can you explain query in hibernate?

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.


1 Answers

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); 
like image 124
Kiavash Avatar answered Oct 19 '22 03:10

Kiavash