Search code examples
hibernatejpaopenjpa

Does OpenJPA have any support for batch insert?


Does OpenJPA have any support for batch insert similar to Hibernate? I haven't found it in the docs, but I'm hoping I missed it. I know JPA doesn't support it in general.


Solution

  • Short answer, yes.

    Longer answer, take the link to Hibernate documentation and replace the Session with a JPA EntityManager.

    EntityManager em = emf.createEntityManager();
    Transaction tx = em.getTransaction();
    
    tx.begin();   
    for ( int i=0; i<100000; i++ ) {
        Customer customer = new Customer(.....);
        em.persist(customer);
        if ( i % 20 == 0 ) { //20, same as the JDBC batch size
            //flush a batch of inserts and release memory:
            em.flush();
            em.clear();
        }
    }
    
    tx.commit();
    em.close();