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

问题描述

好吧,我正在尝试在JPA中进行批量插入,但是我认为这不起作用.

Well, i'm trying to making a batch insert in JPA but i think this don't work.

我的方法是这样的:

public void saveBatch(List<? extends AbstractBean> beans) {
    try {
        begin();
        logger.info("Salvando em batch " + beans.size() + " bean(s)");
        for (int i = 0; i < beans.size(); i++) {
        if (i % 50 == 0) {
            entityManager.flush();
            entityManager.clear();
        }
        entityManager.merge(beans.get(i));

        }
        commit();
    } catch (Exception e) {
        logger.error("Ocorreu um erro ao tentar salvar batch. MSG ORIGINAL: "
                + e.getMessage());
        rollback();
        throw new DAOException("Ocorreu um erro ao tentar salvar batch");
    }
    }

我的想法是休眠状态每产生50行:

My ideia is that each 50 rows the hibernate will make:

insert into tableA values (),(),()...

但是,看着日志,我看到每个merge()命令的一个INSERT链接如下:

But watching the log i see one INSERT for each merge() command link this:

insert into tableA values ()
insert into tableA values ()
insert into tableA values ()
insert into tableA values ()

怎么了?这是正确的吗?

What is wrong ? This is correct ?

推荐答案

默认情况下,Hibernate不启用批处理.您将要考虑以下设置(我认为至少需要batch_size才能使任何批处理插入/更新生效):

Hibernate does not enable batching by default. You will want to consider the following settings (I think at least batch_size is required to get any batch inserts/updates to work):

hibernate.jdbc.batch_size
hibernate.jdbc.batch_versioned_data
hibernate.order_updates (similarly, hibernate.order_inserts)

这篇关于在Hibernate/JPA中使用批处理插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:27
查看更多