hibernate envers:合并和合并保存或更新
我正在开发 spring-hibernate-envers 应用程序。经过大量谷歌搜索后,事情终于对我有用,但我仍然有几个问题。
之前我使用
saveOrUpdate
保存或更新实体。但 当与恩弗斯一起工作时,它是 抛出一个nonUniqueObject
例外。所以我用merge
代替 它起作用了。使用是否正确 为此合并?是否合并
插入 数据库的新对象?我尝试了以下代码:
实体=合并(实体); 保存或更新(实体);
这也奏效了。这是正确的方法吗?我也很好奇为什么 saveOrUpdate
现在没有抛出任何错误。
I am working on an spring-hibernate-envers application. After lot of googling things are finally working for me but i have still got couple of questions.
Earlier i was using
saveOrUpdate
for
saving or updating entities. But
when working with envers it was
throwing anonUniqueObject
exception. So i usedmerge
instead
and it worked. Is it right to use
merge for this? Doesmerge
inserts
new objects to db?I tried following code:
entity=merge(entity); saveOrUpdate(entity);
This also worked. Is it the right way? And also i am curious that why saveOrUpdate
is not throwing any error now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Hibernate 参考 说:
这意味着您可以使用< code>saveOrUpdate() 如果您确定具有相同标识符的对象未与会话关联。否则你应该使用
merge()
。以下代码
之所以有效,是因为
merge()
的结果是一个持久对象,因此它会被saveOrUpdate()
忽略,因此第二行没有任何意义。Hibernate Reference says:
It means that you can use
saveOrUpdate()
if you are sure that the object with the same identifier is not associated with the session. Otherwise you should usemerge()
.The following code
works because the result of
merge()
is a persistent object, therefore it's ignored bysaveOrUpdate()
, so that the second line doesn't make any sense.saveOrUpdate:如果请求的对象是瞬态的(空主键值),则将其保留在数据库中或更新它。条件是会话中只有该实体的一个副本。
合并: Hibernate会首先检查持久化对象中是否已经存在该类型的持久化实例。
语境。它使用对象标识符来检查是否存在。如果存在另一个实例,它会复制状态
将 Detached 对象合并到现有的 Persistence 对象中。如果不存在其他实例,
Hibernate 只是重新附加 Detached 对象。
如果会话包含单个实体的多个副本,则使用最新实体更新所有副本。 在您调用 update 之前,它不会在数据库中更新。
saveOrUpdate: If requested object is transient(null primary key value) then, persist it in database or update it. The condition is that there is only one copy of that entity in session.
merge: Hibernate will first check whether a Persistent instance of that type already exists in the persistent
context. It uses the object identifiers to check on this existence. If another instance exists, it copies the state
of the Detached object into the existing Persistence object. If no other instance exists,
Hibernate just reattaches the Detached object.
If the session contains more then one copy of a single entity, then update all the copy with latest entity. It will not update in database until you call update.