在Hibernate/JPA中使用批处理插入 [英] Using batch insert in 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 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使用JDBC2批处理更新.例如 推荐值在5到30之间
A non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5 and 30
hibernate.jdbc.batch_versioned_data
如果您的JDBC驱动程序返回正确的行,则将此属性设置为true 从executeBatch()计数.通常可以安全地打开此选项. 然后,Hibernate将使用批处理的DML来自动版本化数据. 默认为false.例如真实|错误
Set this property to true if your JDBC driver returns correct row counts from executeBatch(). It is usually safe to turn this option on. Hibernate will then use batched DML for automatically versioned data. Defaults to false. e.g. true | false
hibernate.order_updates (similarly, hibernate.order_inserts)
强制Hibernate通过以下命令的主键值对SQL更新进行排序 项正在更新.这将减少交易死锁 在高度并发的系统中.例如真实|错误
Forces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems. e.g. true | false
这篇关于在Hibernate/JPA中使用批处理插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!