fcartu
fcartu

Reputation: 355

How can insert faster using nhibernate?

I need to insert 1 million of object in an oracle database, right now it takes so much time to do this job, how can i insert faster this object inside the database?

I'm using this code to do it:

using (ISession session = NHibernateHelper.OpenSession())
{
  using (ITransaction tranx = session.BeginTransaction())
  {
     session.Save(movimientoPendiente);
     tranx.Commit();
  }
}

Thanks for your help.

Upvotes: 2

Views: 2015

Answers (3)

psousa
psousa

Reputation: 6726

Use a stateless session and do all the inserts in the same transaction:

using (var session = NHibernateHelper.GetSessionFactory().OpenStatelessSession())
using (var tranx = session.BeginTransaction())
{
    for(...)
    {
        var movimientoPendiente = ...;
        session.Insert(movimientoPendiente);
    }

    tranx.Commit();
}

Upvotes: 4

Rex Morgan
Rex Morgan

Reputation: 3029

Use a single session instead of creating a new connection to the database for each of your records. Jimmy Bogard wrote a good blog post about bulk processing using NHibernate.

Upvotes: 1

Wyatt Barnett
Wyatt Barnett

Reputation: 15673

In general ORMs are not meant for ETL-style work, such as loading 1m records. The fancy stuff they do, such as change tracking, is pretty lost there and is pretty much unneeded overhead. Straight out ADO.NET is your friend here.

But it would probably help if you used one session and one transaction for more than a single record:

using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction tranx = session.BeginTransaction())
{
     foreach (var rec in MyRecords)
     {
        session.Save(movimientoPendiente);
     }
     tranx.Commit();
}

That at least means you aren't building a somewhat expensive session and burning a rather expensive transaction every single time you send a record.

Upvotes: 2

Related Questions