Reusing queries in sleep mode

I use HQL queries in Hibernate and just wonder if I can increase the readiness of reusing application queries.

Usually you need 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 that I donโ€™t want to parse again and again. Is there a way to create a request and reuse itt in another session? Like this:

 Session session; Query q2 = q1.reattach(); q2.setInteger("id",123); List result = q2.list(); 

If Hibernate still uses prepared statements, this should be a noticeable performance boost, especially when combined with ConnectionPool, which caches prepared statements.

EDIT . Reusing queries in sleep mode is usually not required because the query plan is already cached in the QueryPlanCache class. Named queries also provide no improvement, because they are simply used to find the query string, and no plan is associated with them.

In conclusion: it makes no sense to repeat the use of queries in Hibernate. Just remember to use parameterized queries ALWAYS, so keep small plan caches.

+7
source share
2 answers

You can use the Named Query: annotate your Entity class, for example

 @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 startup, when you want to use it, you simply call:

 session.getNamedQuery("Article.findById") .setInteger("id",123); 
+4
source

Named Query as described by Kiavash does what you ask for, but I doubt it gives you any significant performance boost.

Prepared statements are used if your database supports them regardless of whether you use Hibernate Named Queries or not. In most cases, you get rid of the need to parse the HQL query. A named query is more intended for code reuse.

0
source

All Articles