I need to save a large number of objects in a database using sleep mode. Instead of compiling everything at once, I would like to commit as soon as n objects (BATCH_SIZE) are present in the session.
Session session = getSession(); session.setCacheMode(CacheMode.IGNORE); for(int i=0;i<objects.length;i++){ session.save(objects[i]); if( (i+1) % BATCH_SIZE == 0){ session.flush(); session.clear(); } }
I would try something like the above, but I read that session.flush() does not commit changes to the database. Is this the correct code?
Session session = getSession(); session.setFlushMode(FlushMode.COMMIT); session.setCacheMode(CacheMode.IGNORE); session.beginTransaction(); for(int i=0;i<objects.length;i++){ session.save(objects[i]); if( (i+1) % BATCH_SIZE == 0){ session.getTransaction().commit(); session.clear();
source share