分享

Hibernate的各种保存方式的区别(2)

 WindySky 2007-10-10
四,persist和save区别

  这个是最迷离的一对,表面上看起来使用哪个都行,在hibernate reference文档中也没有明确的区分他们。

  这里给出一个明确的区分。(可以跟进src看一下,虽然实现步骤类似,但是还是有细微的差别)

  这里参考http://opensource./projects/hibernate/browse/HHH-1682中的一个说明:

---------------------------------------------------------------------------------

  I found that a lot of people have the same doubt. To help to solve this issue

  I'm quoting Christian Bauer:

  "In case anybody finds this thread……

  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."

---------------------------------------------------------------------------------

  简单翻译一下上边的句子的主要内容:

  1,persist把一个瞬态的实例持久化,但是并"不保证"标识符被立刻填入到持久化实例中,标识符的填入可能被推迟

  到flush的时间。

  2,persist"保证",当它在一个transaction外部被调用的时候并不触发一个Sql Insert,这个功能是很有用的,

  当我们通过继承Session/persistence context来封装一个长会话流程的时候,一个persist这样的函数是需要的。

  3,save"不保证"第2条,它要返回标识符,所以它会立即执行Sql insert,不管是不是在transaction内部还是外部

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多