使用JPA和Spring批量插入 [英] Batch Insert with JPA and Spring

查看:56
本文介绍了使用JPA和Spring批量插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Framework和JPA将bean插入到我的数据库中.我需要插入将近8000个实体,这可能会延迟太多.

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. 为什么应该在Hibernate中禁用二级缓存" hibernate.cache.use_second_level_cache false

当我在Hibernate中设置"hibernate.jdbc.batch_size 20"时,它会像这样插入我的bean吗?

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. 文档说:如果您使用身份标识符生成器,​​则Hibernate透明地在JDBC级别禁用插入批处理.因此,我所有的bean都具有以下配置:

@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?

推荐答案

在Hibernate中,您不能禁用会话级缓存.如果您不想要它,请使用 StatelessSession .这将不会缓存任何内容.

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

此外,Hibernate文档指定了如何进行批量插入.请参见此处.

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

这篇关于使用JPA和Spring批量插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆