Batch inserts with JPA/EJB3

后端 未结 5 498
说谎
说谎 2020-12-01 10:45

Does JPA/EJB3 framework provide standard way to do batch insert operation...? We use hibernate for persistence framework, So I can fall back to Hibernate Session and use com

5条回答
  •  隐瞒了意图╮
    2020-12-01 11:29

    Neither JPA nor Hibernate do provide particular support for batch inserts and the idiom for batch inserts with JPA would be the same as with Hibernate:

    EntityManager em = ...;
    EntityTransaction 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();
    session.close();
    

    Using Hibernate's proprietary API in this case doesn't provide any advantage IMO.

    References

    • JPA 1.0 Specification
      • Section 4.10 "Bulk Update and Delete Operations"
    • Hibernate Core reference guide
      • Chapter 13. Batch processing

提交回复
热议问题