休眠: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?
推荐答案
在《休眠手册》中,您可以看到此示例
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屋!