Hibernate有一些方法,它们以某种方式获取对象并将其放入数据库中。它们之间的区别是什么,什么时候使用哪个,为什么没有一种智能方法知道什么时候使用什么?

到目前为止,我已经确定的方法是:

save () (更新) saveOrUpdate () saveOrUpdateCopy () 合并() persist ()


当前回答

实际上,hibernate save()和persist()方法之间的区别取决于我们使用的生成器类。

If our generator class is assigned, then there is no difference between save() and persist() methods. Because generator ‘assigned’ means, as a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ] In case of other than assigned generator class, suppose if our generator class name is Increment means hibernate it self will assign the primary key id value into the database right [ other than assigned generator, hibernate only used to take care the primary key id value remember ], so in this case if we call save() or persist() method then it will insert the record into the database normally But hear thing is, save() method can return that primary key id value which is generated by hibernate and we can see it by

long s = session.save(k);

在同样的情况下,persist()将永远不会向客户端返回任何值。

其他回答

See the Hibernate Forum for a explanation of the subtle differences between persist and save. It looks like the difference is the time the INSERT statement is ultimately executed. Since save does return the identifier, the INSERT statement has to be executed instantly regardless of the state of the transaction (which generally is a bad thing). Persist won't execute any statements outside of the currently running transaction just to assign the identifier. Save/Persist both work on transient instances, ie instances which have no identifier assigned yet and as such are not saved in the DB. Update and Merge both work on detached instances, ie instances which have a corresponding entry in the DB but which are currently not attached to (or managed by) a Session. The difference between them are what happens to the instance which is passed to the function. update tries to reattach the instance, that means that there must be no other instance of the persistent entity attached to the Session right now, otherwise an exception is thrown. merge, however, just copies all values to a persistent instance in the Session (which will be loaded if it is not currently loaded). The input object is not changed. So merge is more general than update, but may use more resources.

请注意,如果对已分离对象调用更新,无论是否更改对象,数据库中总是会完成更新。如果不是你想要的,你应该使用Session.lock()和LockMode.None。

只有当对象在当前会话范围之外被更改时(当处于分离模式时),才应该调用update。

以下是我对这些方法的理解。这些主要是基于API的,尽管我在实践中没有使用所有这些。

saveOrUpdate 根据某些检查调用save或update。例如,如果不存在标识符,则调用save。否则调用update。

保存 持久化一个实体。如果标识符不存在,将分配标识符。如果有,它本质上是在进行更新。返回生成的实体ID。

更新 尝试使用现有标识符持久化实体。如果不存在标识符,则抛出异常。

saveOrUpdateCopy 这已弃用,不应再使用。取而代之的是……

合并 现在我的知识开始动摇了。这里重要的是瞬态实体、分离实体和持久实体之间的区别。有关对象状态的更多信息,请查看这里。使用save & update,你处理的是持久对象。它们被链接到一个会话,因此Hibernate知道发生了什么变化。但是当你有一个瞬态对象时,就不涉及会话了。在这些情况下,您需要使用合并进行更新,使用持久化进行保存。

坚持 如上所述,这用于瞬态对象。它不返回生成的ID。

╔══════════════╦═══════════════════════════════╦════════════════════════════════╗
║    METHOD    ║            TRANSIENT          ║            DETACHED            ║
╠══════════════╬═══════════════════════════════╬════════════════════════════════╣
║              ║       sets id if doesn't      ║   sets new id even if object   ║
║    save()    ║     exist, persists to db,    ║    already has it, persists    ║
║              ║    returns attached object    ║ to DB, returns attached object ║
╠══════════════╬═══════════════════════════════╬════════════════════════════════╣
║              ║       sets id on object       ║             throws             ║
║   persist()  ║     persists object to DB     ║       PersistenceException     ║
║              ║                               ║                                ║
╠══════════════╬═══════════════════════════════╬════════════════════════════════╣
║              ║                               ║                                ║
║   update()   ║           Exception           ║     persists and reattaches    ║
║              ║                               ║                                ║
╠══════════════╬═══════════════════════════════╬════════════════════════════════╣
║              ║  copy the state of object in  ║    copy the state of obj in    ║
║    merge()   ║     DB, doesn't attach it,    ║      DB, doesn't attach it,    ║
║              ║    returns attached object    ║     returns attached object    ║
╠══════════════╬═══════════════════════════════╬════════════════════════════════╣
║              ║                               ║                                ║
║saveOrUpdate()║           as save()           ║            as update()         ║
║              ║                               ║                                ║
╚══════════════╩═══════════════════════════════╩════════════════════════════════╝

我找到了一个很好的例子来说明所有hibernate保存方法之间的差异:

http://www.journaldev.com/3481/hibernate-session-merge-vs-update-save-saveorupdate-persist-example

总之,根据以上链接:

save ()

我们可以在事务外部调用此方法。如果我们在没有事务的情况下使用它,并且在实体之间有级联,那么只有主实体会被保存,除非我们刷新会话。 因此,如果主对象映射了其他对象,则在提交事务或刷新会话时保存它们。

persist ()

它类似于在事务中使用save(),所以它是安全的,并照顾任何级联对象。

saveOrUpdate ()

可以与事务一起使用,也可以不使用事务,就像save()一样,如果它在没有事务的情况下使用,映射的实体将不会被保存,除非我们刷新会话。 根据所提供的数据将结果插入或更新查询。如果数据存在于数据库中,则执行更新查询。

update ()

当我们知道我们只是在更新实体信息时,应该使用Hibernate更新。该操作将实体对象添加到持久上下文,并在事务提交时跟踪和保存进一步的更改。 因此,即使在调用update之后,如果我们在实体中设置了任何值,它们将在事务提交时被更新。

go()

Hibernate merge可用于更新现有值,但此方法从传递的实体对象创建一个副本并返回它。返回的对象是持久上下文的一部分,并跟踪任何更改,传递的对象不跟踪。这是merge()与其他方法的主要区别。

对于所有这些方法的实际示例,请参考我上面提到的链接,它展示了所有这些不同方法的示例。