gpt4 book ai didi

java - Hibernate 坚持 vs 保存

转载 作者:行者123 更新时间:2023-11-29 07:05:49 25 4
gpt4 key购买 nike

当我试图理解 Hibernate Save 和 persist 之间时,我遇到了这个解释:

persist() is well defined. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec doesn't say that, which is the problem I have with persist().

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.

A method like persist() is required.

save() does not guarantee the same, it returns an identifier, and 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 not good in a long-running conversation with an extended Session/persistence context.

你能帮我理解 persist 的行吗:

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.

这里的事务边界是什么?什么是长时间运行的对话?扩展 session /持久性上下文是什么意思?

还有保存方法:

this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

我知道如果我们在程序中使用 save 方法来保存对象,则不需要像 session.beginTransaction() 和 session.getTransaction().commt() 这样的语句。如果声明在这里说的是同样的话,请告诉我。那么这在长时间运行的对话中有什么用呢?

我是 hibernate 的新手,发现很难理解这些差异,你能帮我理解这些差异吗。

最佳答案

您的问题与 Open Session in View 有关模式 Hibernate 实现。

这个想法是,您可能在 Web 应用程序中有一个原子工作单元,需要在整个特定进程中运行。想象一下在线订购食物。您在一页上登录,在下一页选择披萨和配料,在下一页添加甜点,在下一页添加饮料,并在最后一页付款。您希望整个过程成为一个单一的工作单元。

因此 Hibernate Session 需要在该工作单元开始时打开并在结束时关闭——手动或通过某种容器管理。

在该对话期间调用 persist 不会导致任何数据插入,但会使分离的实体持久化。 Hibernate 将“记录”所有要进行的插入,然后在 session 结束时刷新它们。

与此同时 save 会立即执行插入操作,并从数据库中为您的实体提供一个 ID。这在长时间运行的对话中并不好,因为您希望数据库操作是原子的——全有或全无。可能会发生奇怪的事情,例如多次插入相同的数据。

希望对您有所帮助。

关于java - Hibernate 坚持 vs 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19994098/

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