How to make batches of inserts in sleep mode?

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(); //should I begin a new transaction for next batch of objects? session.beginTransaction(); } } session.getTransaction().commit(); 
+4
source share
1 answer

As far as I can tell, your decision is correct.

There can only be one problem: Depending on how you get the sessions from the SessionFactory, commit can also close your session and you will need to open a new one. To my knowledge, this always happens if you use getCurrentSession () and the context of the stream session. If you use openSession (), the session does not seem to automatically close with a commit.

You can easily verify this with the isOpen () method after the transaction. If the session is closed, you must open a new one before any save () calls.

0
source

All Articles