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

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

问题描述

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

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()

推荐答案

以下是我对方法的理解.主要是基于 API 虽然我不不要在实践中使用所有这些.

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根据某些检查调用 save 或 update .例如.如果不存在标识符,则调用 save.否则调用更新.

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

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

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这已被弃用,不应再使用.取而代之的是...

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

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

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.

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

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

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

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