开发者

Hibernate: Unexpected fetch order for batch fetching

I'm using hibernate's batch fetching to improve query performance. In my persistence.xml I've added the following setting:

<property name="hibernate.default_batch_fetch_size" value="50"/>

I've got an entity A, which has a 1:n relation to an entity B. The data for this relation is fetched lazily. Now I've got the following situation:

  • I load 10000 entities of type A from DB
  • I iterate over those entities and initialize the lazy relation by calling a.getBs().size()
  • When doing so hibernate does not only initialize the dependency for the current entity, but in addition loads the dependency for 49 additional entities from the 开发者_如何学编程list. This behaviour is expected.

The generated SQL looks similar to this:

select
    b0_.SOMETHING as SOMETHING1_1_,
    ...
from
    XYZ.B b0_ 
where
    b0_.A_ID in (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ...
    ) 

My real problem is that hibernate is not loading the entities of the result list in the expected order. When I access the first entry from the list, it doesn't load data for entities 2-50, but it loads data for 49 random entries from the list. (e.g. it may initialize the data of entities 3, 7, 100, 2001, ...). This behaviour is quite strange and I'm wondering how to change it to load data in the expected order.

Current problems, that are related to the described behaviour.

  • Memory usage. While iterating over the list hibernate is initializing a lot of data, which will be required MUCH later. In addition to the algorithm from above I've added some code, which removes processed records from the list and calls session.evict(entity), to make the entity eligible for garbage collection. This is of course not working out now.
  • Query speed is very slow at the beginning of the iteration as hibernate is querying the db for nearly every processed entity. This causes problems as I'm writing the entities to a web application's stream for downloading while processing. As a result the download speed is very slow in the beginning and speeds up when more entities have been loaded to memory and less db calls are required.

Thanks a lot for your help and best regards

Thomas


When you say that Hibernate is not loading the entities in the expected order, have you told it what the expected order is? That is, does the mapping for the Bs contain an order-by attribute? If not, then they have no order in the Hibernate data model and can be loaded in any order (likely the database default).

Otherwise, my understanding is that Hibernate should apply the order-by constraint when looking up the pkeys to load. Hence it might be worth taking this up on the mailing lists as a potential bug.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜