HIbernate commit()和flush() [英] HIbernate commit() and flush()

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

问题描述

我搜索了很多并阅读了关于 org.hibernate.Transaction.commit() org.hibernate.Session.flush() code>很多,知道每种方法的目的,但仍然有一个问题。

手动调用 org.hibernate.Session.flush()方法是否是好习惯?如 org.hibernate.Session 文档中所述,


必须在在提交事务并关闭会话之前(取决于flush-mode,Transaction.commit()调用此方法)。

如果 org.hibernate.Transaction.commit可以解释我手动调用 org.hibernate.Session.flush()的目的吗? ()会自动调用它?



谢谢!

解决方案<在Hibernate手册中,你可以看到这个例子

  Session session = sessionFactory.openSession(); 
Transaction tx = session.beginTransaction();


(int i = 0; i <100000; i ++){
Customer customer = new Customer(.....);
session.save(customer);
if(i%20 == 0){// 20,与JDBC批量大小相同
//刷新一批插入并释放内存:
session.flush();
session.clear();
}
}

tx.commit();
session.close();

如果没有调用flush方法,您的第一级缓存会抛出OutOfMemoryException



你也可以看看这个帖子关于刷新


I googled a lot and read about org.hibernate.Transaction.commit() and org.hibernate.Session.flush() a lot, know purpose of each method, but still have a question.

Is it good practice to call org.hibernate.Session.flush() method by hand? As said in org.hibernate.Session docs,

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

Could you explain me purpose of calling org.hibernate.Session.flush() by hand if org.hibernate.Transaction.commit() will call it automatically?

Thanks!

解决方案

In the Hibernate Manual you can see this example

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

Without the call to the flush method, your first-level cache would throw an OutOfMemoryException

Also you can look at this post about flushing

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

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