0

I have a question/confusion, how to do batch insert when records are in odd number say for example

batchSize = 20;
em.getTransaction().begin();
    for (int i = 0; i < 23; i++){
        Book book = new Book(i, "JPA Batch Insert Example: " + i);
        em.persist(book);

        if (i % batchSize == 0 && i > 0) {
            em.flush();
            em.clear();
        }
    }
    em.getTransaction().commit();

In this example 20 records will be inserted at once but what about rest 3 records what will happen to those 3 records , will it insert if yes then when

Nilendu Kumar
  • 63
  • 1
  • 1
  • 5
  • You need to add logic to insert and commit the odd bits left over. Nothing is automatic. – duffymo Apr 03 '17 at 18:45
  • 1
    Possible duplicate of [Entitymanager.flush() VS EntityManager.getTransaction().commit - What should I prefer?](http://stackoverflow.com/questions/11048177/entitymanager-flush-vs-entitymanager-gettransaction-commit-what-should-i-p) – GreyBeardedGeek Apr 03 '17 at 18:51

1 Answers1

0

You are calling em.getTransaction().commit(); in the end, this is what the Javadoc reads for commit():

Commit the current resource transaction, writing any unflushed changes to the database.

So, it writes all the unflushed changes to database and commits the transaction. In your question, 3 records will be undflushed and will be written to database once for loop finishes.

Answer : You don't need to make any change to your code, it will automatically insert those 3 records (or any remaining records) once for loop is complete.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102