hibernate批量插入 - 如何刷新工作? [英] hibernate batch insert - how flush works?

查看:133
本文介绍了hibernate批量插入 - 如何刷新工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用hibernate在数据库中插入大量数据,我正在查看来自hibernate的批量插入,我使用的是类似于手册中的示例:

I need to insert a lot of data in a database using hibernate, i was looking at batch insert from hibernate, what i am using is similar to the example on the manual:

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

but i see that flush doesn't write the data on the database. Reading about it, if the code is inside a transaction then nothing will be committed to the database until the transaction performs a commit.

那么需要什么呢?使用冲洗/清除?似乎没用,如果数据没有写在数据库上,那么它们就在内存中。

So what is the need to use flush/clear ? seems useless, if the data are not written on the database then they are in memory.

如何强制hibernate在数据库中写入数据?

How can i force hibernate to write data in the database?

谢谢

推荐答案

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

The data is sent to the database, and is not in memory anymore. It's just not made definitively persistent until the transaction commit. It's exacltly the same as if you executes the following sequences of statements in any database tool:

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;

刷新包括执行insert语句。

The flush consists in executing the insert statements.

提交包括执行commit语句。

The commit consists in executing the commit statement.

这篇关于hibernate批量插入 - 如何刷新工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆