Thursday, September 30, 2010

Bulk Data Loading with Hibernate

The most efficient way of loading large amounts of data into Hibernate is using a StatelessSession (provided of course you don't want to keep the objects being loaded in the Persistent Context). The StatelessSession essentially works like a plain JDBC connection with the added bonus of being able to use your mapped persistent classes. You should be able to copy/paste the following into your code:

public void bulkCreate(Collection<?> entities) {
// Open a Stateless Session (this doesn't have a persistence context cache and
// doesn't interact with any other second-level or query cache). Everything
// executed with a Stateless session results in an immediate SQL operation.
StatelessSession session = HibernateUtil.getSessionFactory().openStatelessSession();
session.beginTransaction();
Iterator<?> it = entities.iterator();
while (it.hasNext()) {
session.insert(it.next());
}
session.getTransaction().commit();
session.close();
}

No comments: