您的位置:首页 > 博客中心 > 数据库 >

NHibernate大批量插入数据库的处理方法 NHibernate Batch processing

时间:2022-03-14 01:46

使用NHibernate插入接近100000条记录到数据库,像下面一个例子:

ISession session = sessionFactory.OpenSession();
ITransaction tx = session.BeginTransaction();
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.Save(customer);
}
tx.Commit();
session.Close();

这将在大约50 000条记录的时候抛出OutOfMemoryException并终止。这是因为NHibernate缓存所有新插入Customer实例在session-level缓存。

使新对象持久化时,必须不断地先用Flush()然后Clear() session 去控制一级缓存的大小。

ISession session = sessionFactory.openSession();
ITransaction 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 ADO batch size
        //flush a batch of inserts and release memory:
        session.Flush();
        session.Clear();
    }
}
   
tx.Commit();
session.Close();

 

 

热门排行

今日推荐

热门手游