我需要使用 hibernate 在数据库中插入大量数据,我正在查看 hibernate 的批量插入,我使用的类似于手册上的示例:
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/clear呢?看起来没什么用,如果数据没有写入数据库那么它们就在内存中。
如何强制hibernate将数据写入数据库?
Thanks
数据is发送到数据库,并且不再在内存中。只是在事务提交之前它不会被明确持久化。这与在任何数据库工具中执行以下语句序列完全相同:
begin;
insert into ...
insert into ...
insert into ...
// here, three inserts have been done on the database. But they will only be made
// definitively persistent at commit time
...
commit;
刷新包括执行插入语句。
提交包括执行提交语句。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)