简体   繁体   中英

Using batch insert in Hibernate/JPA

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

My method is this :

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");
    }
    }

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

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

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

A non-zero value enables use of JDBC2 batch updates by Hibernate. eg recommended values between 5 and 30

hibernate.jdbc.batch_versioned_data

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. eg true | false

hibernate.order_updates (similarly, hibernate.order_inserts)

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. eg true | false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM