Batching Statements in NHibernate

Picture the case where you want to insert/manipulate a mass of data using your already in place NHibernate infrastructure.

Usually you would do something like this:

for (int i = 0; i < 100; i++)
{
MyEntity entity = new MyEntity(i);
session.Save(entity);
}

This has the drawback of producing a single INSERT per save call, and thus creating 100 roundtrips to the database; one per insert. Further more the actual INSERT command will be re-constructed for each single Save call.

To circumwent some of these shortcummings you should start a new transaction and wrap all Save calls in this transaction:

ITransaction tx session.BeginTransaction();
for (int i = 0; i < 100; i++)
{
MyEntity entity = new MyEntity(i);
session.Save(entity);
}
tx.Commit();

This will at least reuse the command-object created for the first Save call.

If your’re using MS-SQL you can benefit from further enhancements. NHibernate offers the capability of batching statements. By adding a configuration setting for hibernate.adonet.batch_size with a value greater than 0 will enable batching. In conjunction with the transaction only after the in batch_size specified commands have been recorded this batch is send to the DB. So with a hibernate.adonet.batch_size of 10 the above code would result in 10 roundtrips instead of the original 100.

Leave a Comment.