[英]Hibernate @BatchSize doesn't work as expected after session.flush
我正在使用Hibernate 4.2,並且我有一個包含子實體集合的父實體(一對多,獲取類型為LAZY,並使用@BatchSize(size=100))
注釋@BatchSize(size=100))
。
如果我查詢並加載幾個父實體並調用訪問包含子對象的集合,則hibernate使用@BatchSize
作為預期。 但是如果我調用session,flush然后執行相同的操作,它只為該特定父實體初始化集合。
這是Hibernate預期的行為嗎?
編輯:樣本
List parents = criteria.list() parents.get(0).getXs().get(0) // triggers loading Xs of all parents
VS
List parents = criteria.list() session.flush() parents.get(0).getXs().get(0) // triggers loading Xs of only the first parent
我將回答我自己的問題,因為我認為這會有助於其他人。 我認為這是Hibernate行為,即使它沒有在任何文檔中提到過。 當我們調用Session.flush時,它調用Flushing事件監聽器並且我在AbstractFlushingEventListenrner類中找到了這個代碼
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Post-flushing section
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* 1. Recreate the collection key -> collection map
* 2. rebuild the collection entries
* 3. call Interceptor.postFlush()
*/
protected void postFlush(SessionImplementor session) throws HibernateException {
LOG.trace( "Post flush" );
final PersistenceContext persistenceContext = session.getPersistenceContext();
persistenceContext.getCollectionsByKey().clear();
// the database has changed now, so the subselect results need to be invalidated
// the batch fetching queues should also be cleared - especially the collection batch fetching one
persistenceContext.getBatchFetchQueue().clear();
因此,最后一行清除當前上下文的BatchFetchQueue
因此,如果我正確地得到您的問題,請執行以下操作(偽代碼)
a = loadSomeEntity
b = loadSomeEntity
a.getXs.get(0) // triggers loading of Xs for a and b
VS
b = loadSomeEntity
session.flush
a = loadSomeEntity
a.getXs.get(0) // triggers loading only of Xs for a
這對我來說很奇怪,但是如果你做session.com或session.clear而不是flush,那就可以了,因為現在b不再是會話的一部分,因此它不是批量提取的候選者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.