gpt4 book ai didi

hibernate - 使 hibernate save() 和 update() 作为单个插入优化

转载 作者:行者123 更新时间:2023-12-02 19:07:00 24 4
gpt4 key购买 nike

我想知道如何使用 Hibernate (4) 和 Oracle 设置减少 SQL 更新。

一个简单的例子可能是这样的:

打开一个 session /事务,使用session.save()创建一个新的实体Xyz,处理一些业务逻辑,对Xyz进行一些更改并调用session.update(),然后让 session 正常关闭并通过提交进行 hibernate 到数据库。

提交时,Hibernate 将执行一次插入,然后执行更新 - 但它真正需要做的只是一次插入,但在本例中具有 Xyz 的 latest 属性。

有人有做这类事情的想法/模式吗?或者有什么办法可以改变 Hibernate 的行为吗?或者您对此有何看法 - 这是一个完全的反模式吗?

我知道 Hibernate 足够聪明,可以在一个更新覆盖另一个更新时忽略多个更新 - 那么为什么插入不类似呢?

这个小片段可以重现“问题”:

MyEntity e = new MyEntity("xxx"); 
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(e); e.setName("yyy");
session.getTransaction().commit();
session.close();

顺便说一下,我没有什么值得担心的触发因素。

这个例子非常简单,性能问题可能看起来微不足道,但实际上我正在处理一个更复杂的对象(即多次插入和更新),而且容量很大,因此避免更新会很棒。

最佳答案

Is there a way I could add the object to the session, and it would be marked as persistent, but not call save() (that is, the INSERT will not be generated) until the very end?

考虑重构以使用Session.persist(Object)而不是Session.save(Object)如果你想推迟 INSERT 的执行直到 session 被刷新和/或事务关闭。

摘自 JBoss Hibernate Community documentation 的第 10.2 节:

You can also use persist() instead of save(), with the semantics defined in the EJB3 early draft.

  • persist() makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long running conversations with an extended Session/persistence context.
  • save() does guarantee to return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context.

另一个有用的引用可以在 blog article 的“将它们放在一起”部分顶部的方法到场景网格的左上角单元格中找到。描述 persist() 的行为对于从未持久化的对象,如下所示:

  1. Object added to persistence context as new entity
  2. New entity inserted into database at flush()/commit()

关于hibernate - 使 hibernate save() 和 update() 作为单个插入优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16940818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com