gpt4 book ai didi

java - hibernate 批量插入 - 冲洗如何工作?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:27 24 4
gpt4 key购买 nike

我需要使用 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 不会将数据写入数据库。读到它,如果代码在事务中,那么在事务执行提交之前,不会向数据库提交任何内容。

那么使用 flush/clear 有什么必要呢?似乎没用,如果数据没有写入数据库,那么它们就在内存中。

如何强制hibernate向数据库写入数据?

谢谢

最佳答案

数据发送到数据库,不再在内存中。它只是在事务提交之前没有明确持久化。这与您在任何数据库工具中执行以下语句序列完全相同:

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;

刷新包括执行插入语句。

提交在于执行提交语句。

关于java - hibernate 批量插入 - 冲洗如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8310367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com