【问题标题】:hibernate batch insert - how flush works?休眠批量插入 - 刷新如何工作?
【发布时间】:2011-11-29 12:02:10
【问题描述】:

我需要使用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 吗?好像没啥用,如果数据没有写到数据库里就在内存里。

如何强制休眠将数据写入数据库?

谢谢

【问题讨论】:

    标签: java hibernate transactions


    【解决方案1】:

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

    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;
    

    刷新在于执行插入语句。

    提交在于执行提交语句。

    【讨论】:

      【解决方案2】:

      数据将被写入数据库,但根据事务隔离级别,在事务提交之前您不会看到它们(在其他事务中)。

      使用一些 sql 语句记录器,打印通过数据库连接传输的语句,然后您将看到语句被发送到数据库。

      【讨论】:

        【解决方案3】:

        为了获得最佳性能,您还必须提交事务。刷新和清除会话会清除休眠缓存,但数据会移动到 JDBC 连接缓存,并且仍然未提交(不同的 RDBMS / 驱动程序表现出不同的行为) - 您只是将问题转移到其他地方而没有真正的性能改进。

        【讨论】:

          【解决方案4】:

          在提到的位置有flush() 也可以节省您的内存,因为您的会话将被定期清除。否则,您将在内存中有 100000 个对象,并且可能会因更大的计数而耗尽内存。查看this article

          【讨论】:

            猜你喜欢
            • 2015-08-01
            • 1970-01-01
            • 2020-09-26
            • 2015-09-08
            • 1970-01-01
            • 1970-01-01
            • 2012-11-18
            • 2012-08-14
            • 2011-12-07
            相关资源
            最近更新 更多