休眠:flush() 和 commit() [英] Hibernate: flush() and commit()
问题描述
单独调用 org.hibernate.Session.flush()
是个好习惯吗?
Is it good practice to call org.hibernate.Session.flush()
separately?
如org.hibernate.Session
文档所述,
必须在工作单元结束时调用,在提交事务和关闭会话之前(取决于刷新模式,Transaction.commit() 调用此方法).
Must be called at the end of a unit of work, before commiting the transaction and closing the session (depending on flush-mode, Transaction.commit() calls this method).
如果 org.hibernate.Transaction.commit()
已经会调用 flush()
,你能不能明确地解释一下调用它的目的?
Could you explain the purpose of calling flush()
explicitely if org.hibernate.Transaction.commit()
will do it already?
推荐答案
在 Hibernate Manual 中可以看到这个例子
In the Hibernate Manual you can see this example
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for (int i = 0; i < 100000; i++) {
Customer customer = new Customer(...);
session.save(customer);
if (i % 20 == 0) { // 20, same as the JDBC batch size
// flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
如果没有调用flush方法,你的一级缓存会抛出一个OutOfMemoryException
Without the call to the flush method, your first-level cache would throw an OutOfMemoryException
这篇关于休眠:flush() 和 commit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!