Menu

Batch Processing

Batch Processing

Why Batching Matters

Inserting thousands of rows one statement at a time is slow. JDBC batching groups many statements into one round trip, and Hibernate uses it when it is configured.

Two more points affect memory. The persistence context keeps every persisted entity, so a large loop must flush and clear it regularly. Also, IDENTITY keys disable insert batching, so use a sequence for bulk inserts.

hibernate.jdbc.batch_size=50
hibernate.order_inserts=true
hibernate.order_updates=true
sessionFactory.inTransaction(session -> {
    for (int i = 1; i <= 10000; i++) {
        session.persist(new Student("Student " + i));
        if (i % 50 == 0) {
            session.flush();
            session.clear();
        }
    }
});

Code Explanation:

  • hibernate.jdbc.batch_size sets how many statements go in one batch.
  • order_inserts and order_updates sort statements by entity type, so more of them can be batched together.
  • Every 50 objects, flush() sends the batch and clear() empties the persistence context.
  • Without clear(), memory use grows with every entity and can end in an OutOfMemoryError.

For very large jobs, StatelessSession is another option. It has no persistence context, dirty checking, or cascading, and it works directly with insert(), update(), and delete(). Open it with sessionFactory.openStatelessSession().


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details