【发布时间】:2012-08-28 16:06:20
【问题描述】:
我正在使用 Hibernate 4.1.6,但在构建列表的速度方面存在问题。我正在运行以下查询。
public void doQuery(final Baz baz){
final Query query = getSessionFactory().getCurrentSession().createQuery(
"select c.id, foo.someValue from Foo as foo "+
"join foo.a as a"+
"join foo.b as b "+
"join b.c as c "+
"where baz=:baz"
);
query.setParameter("baz", baz);
Long start=System.currentTimeMillis();
final List<Object[]> list = query.list();
Long end=System.currentTimeMillis();
System.out.println((end-start));
}
我设置了休眠调试以获取发送到数据库的实际查询。我直接在数据库中运行了该查询,它在 0.015 毫秒内返回了 23,000 行。所以,我猜查询不是问题。上面的示例显示创建该列表大约需要 32 秒。有什么办法可以加快速度吗?
更新:我尝试使用使用休眠调试查询的 createSQLQuery() 方法,它的运行速度与 createQuery() 方法一样慢。
更新:我尝试使用无状态会话,但运行速度一样慢。
更新:我输出了一些统计信息(将 hibernate.generate_statistics 标志设置为 true),但对我来说没有什么令人担忧的:
Hibernate SessionFactory Statistics [
Number of connection requests[4]
Number of flushes done on the session (either by client code or by hibernate[3]
The number of completed transactions (failed and successful).[3]
The number of transactions completed without failure[3]
The number of sessions your code has opened.[4]
The number of sessions your code has closed.[3]
Total number of queries executed.[4]
Time of the slowest query executed.[28258]
the number of collections fetched from the DB.[6]
The number of collections loaded from the DB.[6]
The number of collections that were rebuilt[0]
The number of collections that were 'deleted' batch.[0]
The number of collections that were updated batch.[0]
The number of your objects deleted.[0]
The number of your objects fetched.[1]
The number of your objects actually loaded (fully populated).[204]
The number of your objects inserted.[1]
The number of your object updated.[0]
]
Hibernate SessionFactory Query Statistics [
total hits on cache by this query[0]
total misses on cache by this query[0]
total number of objects put into cache by this query execution[0]
Number of times this query has been invoked[1]
average time for invoking this query.[28258]
maximum time incurred by query execution[28258]
minimum time incurred by query execution[28258]
Number of rows returned over all invocations of this query[23303]
]
更新:从本机查询的 ScrollableResults 执行 next() 时,我看到同样的缓慢。请注意,我在循环中什么也没做。
ScrollableResults results = query.scroll();
Long start=System.currentTimeMillis();
while (results.next()) {
//do nothing
}
Long end=System.currentTimeMillis();
System.out.println((end-start));
【问题讨论】:
-
可能是一个未提交的交易阻碍了工作。
-
您可能想要打印出您的休眠 sql。很可能有 n+1 选择问题。
-
乔丹,我不知道有任何交易阻碍了这个查询。约翰,我确实打印了上面提到的sql,查询很好。
-
那么初始查询可能没问题,您最终会看到额外的选择吗?或者你只看到一个查询,应该以
Hibernate:开始 -
你发现发生了什么吗?