Batch Insert with JPA and Spring

我只是一个虾纸丫 提交于 2021-02-19 11:43:21

问题


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?


回答1:


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(); 


来源:https://stackoverflow.com/questions/25949777/batch-insert-with-jpa-and-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!