简体   繁体   中英

Batch Insert with JPA and Spring

I'm using Spring Framework and JPA to insert beans into my database. I need to insert almost 8000 entities, and this can delay too much.

  1. Why should I disable "second level cache" in Hibernate hibernate.cache.use_second_level_cache false

  2. When I set a "hibernate.jdbc.batch_size 20" in Hibernate, will it insert my beans like this?

INSERT INTO VALUES (1),(2),(3)...(20);
INSERT INTO VALUES (21),(2),(3)...(40);

  1. The documentation says: "Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.". So, all my beans have this configuration:

@Id
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
private Integer id;

When I'm using this identity above, is the batch insert disabled? How can I solve this?

In Hibernate you cannot disable the session level cache. If you don't want it, use StatelessSession . This will not cache anything.

Furthermore, Hibernate documentation specifies how to do batch insert. See here .

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM