问题
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.
Why should I disable "second level cache" in Hibernate
hibernate.cache.use_second_level_cache false
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);
- 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