简体   繁体   中英

INSERT multiple entities in a single transaction | Hibernate, JPA

I'm trying to create a POST endpoint, using spring MVC, that is responsible for creating multiple entity objects.

At the service layer, the code looks something like this

entities.forEach(entity -> entityManager.persist(entity))

Will this be done in a single unit of work, or the rows will be inserted one by one?

Well, inserts will always be one by one and Hibernate will process them that way. However, you can enable JDBC batch inserts which might require some reordering of the insert statements, eg when dependent entities need to be inserted as well.

As an example, if A has a reference to B and you want to insert A1 and B1 as well as A2 and B2 then Hibernate would have to reorder that to A1, A2, B1, B2 (or more likely B1, B2, A1, A2 if A has the foreign key) - which is something you'd need to enable.

Note that to use batching everything would have to run in the same transaction, ie the line you've posted would have to run in a JTA transaction or Hibernate session context.

Documentation for Hibernate 5.4.20: https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#batch

A few notes though:

  • Having Hibernate log the SQL statements might give the impression that no batching occurs but that's just a logging issue.
  • If your service is going to create a large number of entities in one transaction you might want to take some extra steps to prevent dirty checks etc. having a negative effect on performance (eg by splitting the batch and clearing first level cache after inserting X entities - ideally X would be the JDBC batch size).

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