简体   繁体   English

在单个事务中插入多个实体 | Hibernate, JPA

[英]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.我正在尝试使用 spring MVC 创建一个 POST 端点,该端点负责创建多个实体对象。

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.好吧,插入总是一个接一个,Hibernate 会以这种方式处理它们。 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.但是,您可以启用 JDBC 批量插入,这可能需要对插入语句进行一些重新排序,例如,当还需要插入依赖实体时。

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.例如,如果 A 引用了 B,并且您想要插入 A1 和 B1 以及 A2 和 B2,那么 Hibernate 将不得不将其重新排序为A1, A2, B1, B2 (或者更可能是B1, B2, A1, A2如果 A 有外键) - 这是你需要启用的东西。

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.请注意,要使用批处理,所有内容都必须在同一个事务中运行,即您发布的行必须在 JTA 事务或 Hibernate session 上下文中运行。

Documentation for Hibernate 5.4.20: https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#batch Hibernate 5.4.20 的文档: https://docs.jboss.org/hibernate/stable/orm/user_guide/htmlUsering.html#le

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.让 Hibernate 记录 SQL 语句可能会给人一种印象,即没有发生批处理,但这只是一个日志记录问题。
  • 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).如果您的服务要在一个事务中创建大量实体,您可能需要采取一些额外的步骤来防止脏检查等对性能产生负面影响(例如,在插入 X 个实体后拆分批处理并清除一级缓存- 理想情况下,X 是 JDBC 批量大小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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