在Hibernate中检查分离的实体 [英] Check for detached entity in Hibernate

查看:117
本文介绍了在Hibernate中检查分离的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,如果一个对象是一个分离的实体,Hibernate是如何识别的。我不想要任何具体的方法,只是想了解背后的机制。

从JBoss文档:


分离 - 分离的实例是持久对象
,但其Session已关闭。当然,该对象的引用仍然是
有效的,并且分离的实例甚至可以在
这个状态下被修改。一个分离的实例可以在稍后的时间点重新连接到一个新的会话
,使得它(和所有的修改)
再次持久。该功能为需要用户思考时间的长
运行工作单元启用编程模型。我们称它们为
应用程序事务,即从用户的角度来看
的一个工作单元。



<因此,Hibernate基本上跟踪会话和附加对象。 与该会话相关联的任何持久化对象都将被分离并变得像其他任何POJO一样。

因此,Hibernate做的是:


  1. 在对象引用或会话中调用 session.evict() .clear()从会话中删除对象。

  2. Hibernates持久性管理器依赖于标识符的存在来确定对象的状态。如果一个对象有一个标识符,那么这个对象就是Persistent,如果它不属于一个会话,那么它就是 DETACHED
  3. 分离的对象可以重新关联并且在打开新会话后同步到数据库。

  4. 调用 session.update()会话。另外,对于Detached对象引用,saveOrUpdate()会将 Detached对象转换回持久状态
  5. 当一个Detached对象被重新连接时,数据库用对象的当前状态更新;以包含处于分离状态时所做的更改。

可以找到一个很好的参考这里


I just wonder how Hibernate identifies if an object is a detached entity. I am not asking for any specific method, just want to understand the mechanism behind.

解决方案

From JBoss Docs:

Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

So Hibernate basically keeps track of the sessions and attached objects. Any object that is associated with that session for persistence becomes detached and becomes like any other POJO.

So what Hibernate does is:

  1. Calls session.evict() on the object reference or session.clear() which removes an object from session.
  2. Hibernates persistent manager relies on the existence of an identifier to determine the state of an object. If an object has an identifier, then the object is Persistent, If it does not belong to a session then it is DETACHED.
  3. Detached objects can be reassociated and synchronized to the database after a new session is opened.
  4. Calling session.update() or session.saveOrUpdate() on a Detached object reference transitions the Detached object back to the Persistent state.
  5. When a Detached object is reattached the database is updated with object’s current state; to include changes made while it was in detached state.

A good reference can be found here.

这篇关于在Hibernate中检查分离的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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