From documentation
If we have a case where we need to insert 1000 000 rows/objects:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.save(customer);
if ( i % 20 == 0 ) { //20, same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
Why we should use that approach? What kind of benefit it brings us comparing to StatelessSession one:
StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.insert(customer);
}
tx.commit();
session.close();
I mean, this ("alternative") last example does not use memory, no need to synchronize, clean out of the cache, then this supposed to be best practice for cases like this? Why to use previous one then?