简体   繁体   中英

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.

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); 

Named Query as described by Kiavash does what you are asking but I doubt that it gives you any kind of significant performance boost.

Prepared statements are used if your database supports them regardless if you are using Hibernate's Named Queries or not. At most you are saving the trouble of parsing HQL query. Named Query is more intended for code reuse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM