Hibernate中不同的保存方法有什么区别? [英] What are the differences between the different saving methods in Hibernate?

查看:103
本文介绍了Hibernate中不同的保存方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hibernate有一些方法可以用这种或那种方式把你的对象放到数据库中。它们之间有什么区别,什么时候使用它,为什么不存在一种知道何时使用它的智能方法?



我已经确定的方法到目前为止:
$ b


  • save()

  • update()
  • $ b $ ()
  • saveOrUpdateCopy()

  • merge() / li>

解决方案

这是我对这些方法的理解。虽然这些主要基于 API ,但我仍然'b
$ b

saveOrUpdate
根据一些检查调用保存或更新。例如。如果不存在标识符,则调用保存。否则会更新。



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



更新
尝试使用现有标识符来持久保存实体。如果没有标识符存在,我相信会引发异常。



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



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



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


Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?

The methods that I have identified thus far are:

  • save()
  • update()
  • saveOrUpdate()
  • saveOrUpdateCopy()
  • merge()
  • persist()

解决方案

Here's my understanding of the methods. Mainly these are based on the API though as I don't use all of these in practice.

saveOrUpdate Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called.

save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.

update Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown.

saveOrUpdateCopy This is deprecated and should no longer be used. Instead there is...

merge Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, take a look here. With save & update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving.

persist As mentioned above, this is used on transient objects. It does not return the generated ID.

这篇关于Hibernate中不同的保存方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆