我正在使用Hibernate 4.1.6,並且遇到了構建列表的速度問題。我正在運行以下查詢。爲什麼Hibernate的query.list()很慢?
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));
}
我設置了hibernate調試以獲取發送到數據庫的實際查詢。我直接在數據庫中運行該查詢,並在0.015 ms內返回了23,000行。所以,我猜猜查詢不是問題。上面的例子顯示它需要大約32秒來創建該列表。有什麼可以加快速度的嗎?
更新:我嘗試使用使用hibernate調試查詢的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下一個()的時候從本地查詢。請注意,我在循環中沒有做任何事情。
ScrollableResults results = query.scroll();
Long start=System.currentTimeMillis();
while (results.next()) {
//do nothing
}
Long end=System.currentTimeMillis();
System.out.println((end-start));
可能是未提交交易阻止了作品。 –
你可能想打印出你的hibernate sql。最有可能有一個n + 1選擇問題。 –
約旦,我不知道任何交易阻止這個查詢。約翰,我沒有打印出上面提到的sql,查詢很好。 – user973479