Portable JPA / Bulk Insert

I just jumped on a function written by someone else that seems a bit inefficient, but my JPA knowledge is not so good as to find a portable solution that is not related to Hibernate.

In a nutshell, the Dao method, called in a loop to insert each of the new entities, executes "entityManager.merge (object);".

Is there a way defined in the JPA specifications to pass a list of entities to the Dao method and insert bulk / batch instead of invoking merge for each individual object?

Plus, since the Dao method is annotated with "@Transactional". I am wondering if each individual merge call occurs as part of its own transaction ... which would not help performance.

Any idea?

+3
source share
2 answers

There is no batch insert operation in vanilla JPA.

Yes, each insert will be performed as part of its own transaction. An attribute @Transactional(without qualifiers) means the distribution level REQUIRED(create a transaction if it does not already exist). Assuming you have:

public class Dao {
  @Transactional
  public void insert(SomeEntity entity) {
    ...
  }
}

do the following:

public class Batch {
  private Dao dao;

  @Transactional
  public void insert(List<SomeEntity> entities) {
    for (SomeEntity entity : entities) {
      dao.insert(entity);
    }
  }

  public void setDao(Dao dao) {
    this.dao = dao;
  }
}

Thus, the entire group of inserts is wrapped in a single transaction. If you are talking about a very large number of inserts, you can split it into groups of 1000, 10000, or everything that works, since a sufficiently large uncommitted transaction can starve from the resource database and, possibly, a failure due to size only.

Note. @Transactional- Spring annotation. See Transaction Management from the Spring Directory.

+6

, , :

@Entity
public class SomeEntityBatch {

    @Id
    @GeneratedValue
    private int batchID;
    @OneToMany(cascade = {PERSIST, MERGE})
    private List<SomeEntity> entities;

    public SomeEntityBatch(List<SomeEntity> entities) {
        this.entities = entities;
    }

}

List<SomeEntity> entitiesToPersist;
em.persist(new SomeEntityBatch(entitiesToPersist));
// remove the SomeEntityBatch object later

- , .

, - , . SQL, JPA, .

0

Source: https://habr.com/ru/post/1716603/


All Articles