Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed up bulk insert operations with NHibernate

I want to speed up bulk insert operations with NHibernate 3.2 on Oracle 11g. To do this I tried

Session.Save(entity);
Session.Flush();
Session.Clear();

... in my foreach loop but got an exception caused by objects missing in the Session:

failed to lazily initialize a collection of role: MyClass.PropertyX, no session or session was closed

Another attempt was to set the batch size:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
    <property name="connection.connection_string">xxx</property>
    <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
    <property name="adonet.batch_size">50</property>
    <property name="query.substitutions">true=1, false=0</property>
    <property name="proxyfactory.factory_class">NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate</property>
  </session-factory>
</hibernate-configuration>

additionally I set Session.SetBatchSize(50) in my code an got the following exception:

No batch size was defined for the session factory, batching is disabled. Set adonet.batch_size = 1 to enable batching.

The only location where this exception is thrown is NonBatchingBatcher, so it looks like my session has the wrong batcher.

What is wrong here? How can I speed up batch inserts with NHibernate (without using statlese sessions)?

like image 837
deamon Avatar asked Mar 30 '12 13:03

deamon


1 Answers

Following should work,

var testObjects = CreateTestObjects(500000);

var stopwatch = new Stopwatch();
stopwatch.Start();
using (IStatelessSession session = sessionFactory.OpenStatelessSession())
using (ITransaction transaction = session.BeginTransaction())
{
    foreach (var testObject in testObjects)
        session.Insert(testObject);
    transaction.Commit();
}

stopwatch.Stop();
var time = stopwatch.Elapsed;

Ref : http://nhibernate.info/blog/2008/10/30/bulk-data-operations-with-nhibernate-s-stateless-sessions.html

like image 140
Low Flying Pelican Avatar answered Nov 03 '22 02:11

Low Flying Pelican