关于 Hibernate session.flush() 的问题 [英] Question about Hibernate session.flush()

查看:18
本文介绍了关于 Hibernate session.flush() 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想询问flush方法在以下情况下究竟做了什么:

I want to inquire about what actually the flush method does in the following case:

for (int i = 0; i < myList.size(); i++) {
    Car c = new Car( car.get(i).getId(),car.get(i).getName() );
    getCurrentSession().save(c);
    if (i % 20 == 0)
        getCurrentSession().flush();
}

这是否意味着迭代20次后,清空缓存,然后把持有的20个内存对象实际保存在数据库中?

Does this means that after the iteration 20, the cache is flushed, and then the 20 held memory objects are actually saved in the database ?

谁能向我解释当条件为真时会发生什么.

Can someone please explain to me what will happen when the condition is true.

推荐答案

来自Session#flush:

强制刷新此会话.必须是在工作单元结束时调用,在提交交易之前和关闭会话(取决于flush-mode, Transaction.commit()调用此方法).

Force this session to flush. Must be called at the end of a unit of work, before committing the transaction and closing the session (depending on flush-mode, Transaction.commit() calls this method).

Flushing 是同步底层的过程具有持久性的持久存储状态保存在内存中.

Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.

换句话说,flush 告诉 Hibernate 执行同步 JDBC 连接状态和会话级缓存中对象状态所需的 SQL 语句.并且条件 if (i % 20 == 0) 将使每个 i 20 的倍数发生.

In other words, flush tells Hibernate to execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in the session-level cache. And the condition if (i % 20 == 0) will make it happen for every i multiple of 20.

但是,新的 Car 实例仍然会保存在会话级缓存中,对于大的 myList.size(),你会吃所有内存并最终得到 OutOfMemoryException.为避免这种情况,文档中描述的模式是定期flush AND clear 会话(与 JDBC 批处理大小相同)) 以保留更改,然后分离实例以便它们可以被垃圾收集:

But, still, the new Car instances will be held in the session-level cache and, for big myList.size(), you're going to eat all memory and ultimately get an OutOfMemoryException. To avoid this situation, the pattern described in the documentation is to flush AND clear the session at regular intervals (same size as the JDBC batch size) to persist the changes and then detach the instances so that they can be garbage collected:

当使新对象持久化时刷新()然后清除()会话定期控制大小一级缓存.

13.1. Batch inserts

When making new objects persistent flush() and then clear() the session regularly in order to control the size of the first-level cache.

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();

文档在同一章中提到了如何设置 JDBC 批量大小.

The documentation mentions in the same chapter how to set the JDBC batch size.

这篇关于关于 Hibernate session.flush() 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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