简体   繁体   English

在Hibernate中重用查询

[英]Reusing Queries in Hibernate

I use HQL queries in Hibernate, and just wondered, if I could increase the preformance of my app reusing queries. 我在Hibernate中使用HQL查询,只是想知道,如果我可以增加我的应用程序重用查询的性能。

Usually you have to create a new Query object for each session: 通常,您必须为每个会话创建一个新的Query对象:

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. 现在我在HQL中有相对复杂的查询,我不想一遍又一遍地解析。 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. 如果Hibernate无论如何都使用预处理语句,这应该是一个值得注意的性能提升,特别是与缓存预准备语句的ConnectionPool结合使用时。

EDIT : Reusing Queries in Hibernate is usually not needed, because the query plan is already cached in the class QueryPlanCache anyway. 编辑 :通常不需要在Hibernate中重用查询,因为无论如何查询计划已经缓存在QueryPlanCache类中。 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. 总结一下:在Hibernate中重用Queries是没有用的。 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. Kiavash描述的命名查询可以满足您的需求,但我怀疑它能为您带来任何显着的性能提升。

Prepared statements are used if your database supports them regardless if you are using Hibernate's Named Queries or not. 如果您的数据库支持它们,则使用准备语句,无论您是否使用Hibernate的命名查询。 At most you are saving the trouble of parsing HQL query. 最多可以省去解析HQL查询的麻烦。 Named Query is more intended for code reuse. 命名查询更适用于代码重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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