我有一个刚刚转换为 Spring Data JPA 的项目。该项目使用 Hibernate Search,我需要一种方法来索引数据库中现有的(约 1500 万条)记录。
由于我要处理如此大量的记录,我不能使用 Hibernate Search 的 MassIndexer,因为这会导致内存不足的问题。
从我读到的(这里:http ://docs.jboss.org/hibernate/search/4.2/reference/en-US/html/manual-index-changes.html#search-batchindex ),建议的方式这样做是这样的:
fullTextSession.setFlushMode(FlushMode.MANUAL);
fullTextSession.setCacheMode(CacheMode.IGNORE);
transaction = fullTextSession.beginTransaction();
//Scrollable results will avoid loading too many objects in memory
ScrollableResults results = fullTextSession.createCriteria( Email.class )
.setFetchSize(BATCH_SIZE)
.scroll( ScrollMode.FORWARD_ONLY );
int index = 0;
while( results.next() ) {
index++;
fullTextSession.index( results.get(0) ); //index each element
if (index % BATCH_SIZE == 0) {
fullTextSession.flushToIndexes(); //apply changes to indexes
fullTextSession.clear(); //free memory since the queue is processed
}
}
transaction.commit();
但是,我想注入我在 Spring 中配置的实体管理器。
我已经读到我可以通过使用getDelegate()
实体管理器上的方法来获取 Hibernate 会话,但这会导致一个错误,指出只要我尝试在会话上设置任何属性,Hibernate 会话就会关闭:
public void reindexListings() throws InterruptedException {
Session session = (Session) em.getDelegate();
FullTextSession fts = Search.getFullTextSession(session);
try {
fts.setFlushMode(FlushMode.MANUAL);
} catch (Exception e) {
// Throws stack trace here stating that the Hibernate session is closed.
e.printStackTrace();
}
fts.setCacheMode(CacheMode.IGNORE);
Transaction transaction = fts.beginTransaction();
// Scrollable results will avoid loading too many objects in memory
ScrollableResults results = fts.createCriteria(EListing.class)
.setFetchSize(25).scroll(ScrollMode.FORWARD_ONLY);
int index = 0;
while (results.next()) {
index++;
fts.index(results.get(0)); // index each element
if ((index % 25) == 0) {
fts.flushToIndexes(); // apply changes to indexes
fts.clear(); // free memory since the queue is processed
}
}
transaction.commit();
}
我还读到我可以HibernateUtil
用来获取会话(http://www.17od.com/2006/11/06/using-managed-sessions-in-hibernate-to-ease-unit-testing/),但同样,这并没有使用我的实体管理器。
不确定到目前为止我是否走在正确的轨道上,或者我是否需要以完全不同的方式来做这件事,但到目前为止我发现的任何东西似乎都不起作用。