便携式 JPA 批量/批量插入
我刚刚开始使用其他人编写的一个功能,该功能似乎效率稍低,但我对 JPA 的了解并不足以找到非 Hibernate 特定的可移植解决方案。
简而言之,在循环中调用的 Dao 方法插入每个新实体会执行“entityManager.merge(object);”。
JPA 规范中是否定义了一种方法来将实体列表传递给 Dao 方法并执行批量插入,而不是为每个对象调用合并?
另外,由于 Dao 方法是用“@Transactional”注释的,我想知道是否每个合并调用都发生在它自己的事务中......这对性能没有帮助。
有什么想法吗?
I just jumped on a feature written by someone else that seems slightly inefficient, but my knowledge of JPA isn't that good to find a portable solution that's not Hibernate specific.
In a nutshell the Dao method called within a loop to insert each one of the new entities does a "entityManager.merge(object);".
Isnt' there a way defined in the JPA specs to pass a list of entities to the Dao method and do a bulk / batch insert instead of calling merge for every single object?
Plus since the Dao method is annotated w/ "@Transactional" I'm wondering if every single merge call is happening within its own transaction... which would not help performance.
Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,普通 JPA 中没有批量插入操作。
是的,每个插入都将在其自己的事务中完成。
@Transactional
属性(没有限定符)表示REQUIRED
的传播级别(如果尚不存在则创建一个事务)。假设你有:你这样做:
这样整个插入组就会被包装在一个事务中。如果您正在谈论大量插入,您可能需要将其分成 1000 个、10000 个或任何大小的组,因为足够大的未提交事务可能会使数据库资源匮乏,并且可能仅由于大小而失败。
注意:
@Transactional
是一个 Spring 注释。请参阅 Spring 参考中的事务管理。No there is no batch insert operation in vanilla JPA.
Yes, each insert will be done within its own transaction. The
@Transactional
attribute (with no qualifiers) means a propagation level ofREQUIRED
(create a transaction if it doesn't exist already). Assuming you have:you do this:
That way the entire group of inserts gets wrapped in a single transaction. If you're talking about a very large number of inserts you may want to split it into groups of 1000, 10000 or whatever works as a sufficiently large uncommitted transaction may starve the database of resources and possibly fail due to size alone.
Note:
@Transactional
is a Spring annotation. See Transactional Management from the Spring Reference.如果您心情狡猾,您可以做的是:
由于级联,这将导致实体被插入到单个操作中。
我怀疑这样做比简单地将单个对象保留在循环中是否有任何实际优势。查看 JPA 实现发出的 SQL 并进行基准测试会很有趣。
What you could do, if you were in a crafty mood, is:
Because of the cascade, that will cause the entities to be inserted in a single operation.
I doubt there is any practical advantage to doing this over simply persisting individual objects in a loop. It would be an interesting to look at the SQL that the JPA implementation emitted, and to benchmark.