[英]Hibernate Query runs slow in the system, but fast when run directly
I have a problem similar to the on in this weeks podcast. 我有一个与本周播客相似的问题。
We have a Java application using hibernate with Sql Server 2005. 我们有一个使用Hibernate和Sql Server 2005的Java应用程序。
Hibernate is generating a Query for us that is taking nearly 20 minutes to complete. Hibernate正在为我们生成一个查询,需要将近20分钟才能完成。
If we take the same query using show_sql and replace the questions marks with constant value the answer is returned immediately. 如果我们使用show_sql进行相同的查询并用常量值替换问号,则会立即返回答案。
I think we need option(recompile), but I can't figure out how to do that with HQL. 我认为我们需要选项(重新编译),但我无法弄清楚如何使用HQL。
Please help! 请帮忙!
From the description of your problem, it sounds like you're running into parameter sniffing. 从你的问题的描述,听起来你正在遇到参数嗅探。 Essentially, SQL Server is creating a query plan based on an older set of parameter values that were passed in and which do not create an effective execution plan for the currently running query.
实质上,SQL Server正在基于传入的一组较旧的参数值创建查询计划,这些参数值不会为当前运行的查询创建有效的执行计划。
Typically I resolve this issue by passing the parameter values into local variables and using those in my query or by using OPTION (RECOMPILE). 通常我通过将参数值传递给局部变量并使用我的查询中的那些或使用OPTION(RECOMPILE)来解决此问题。 However, since you are using Hibernate my usual solution isn't an option for you.
但是,由于您使用的是Hibernate,我通常的解决方案不适合您。 As I understand it, the best option is going to be to use Hibernate to run a native SQL query using prepareStatement() or createSQLQuery() which, unfortunately, removes some of the benefits of using Hibernate.
据我了解,最好的选择是使用Hibernate使用prepareStatement()或createSQLQuery()运行本机SQL查询,遗憾的是,它消除了使用Hibernate的一些好处。
In my experience, the main problem with complex queries in Hibernate is not the query itself, but rather the creation of all the objects representing the result set. 根据我的经验,Hibernate中复杂查询的主要问题不是查询本身,而是创建表示结果集的所有对象。
In my case at work, we had a very large domain model, with lots of couplings, so that even fetching one single object from the database was quite expensive because that object was linked to other objects, which in turn were linked to other objects and so on. 在我的工作中,我们有一个非常大的域模型,有很多耦合,所以即使从数据库中取出一个单个对象也是非常昂贵的,因为该对象链接到其他对象,而这些对象又链接到其他对象和等等。
For us, more use of lazy loading solved at least parts of the problem. 对我们来说,更多使用延迟加载至少解决了部分问题。 Smart caching helped even more.
智能缓存帮助更多。 What I learned was that in the future, I'll allow more loose coupling between domain classes.
我学到的是,在未来,我将允许域类之间更松散的耦合。
You should post your mapping and HQL statement. 您应该发布您的映射和HQL语句。 If you are using "join" in your HQL, you might want to take a look what exactly is fetched by Hibernate.
如果你在HQL中使用“join”,你可能想看一下Hibernate究竟取得了什么。 It might turn out that the request itself is simple, but Hibernate is fetching tons of data before the it gets to it.
可能会发现请求本身很简单,但Hibernate在获取数据之前就会获取大量数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.