Why need detached entities in JPA?

前端 未结 6 590
礼貌的吻别
礼貌的吻别 2021-01-31 09:28

There are always so many questions related to issues with detached entities!

First, they often cause LazyInitializationException in Hibernate. Yes, there ar

6条回答
  •  被撕碎了的回忆
    2021-01-31 09:58

    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.

    References Hibernate DOc

    Why?

    The Session caches every object that is in a persistent state (watched and checked for dirty state by Hibernate). If you keep it open for a long time or simply load too much data, it will grow endlessly until you get an OutOfMemoryException. One solution is to call clear() and evict() to manage the Session cache,keeping a Session open for the duration of a user session also means a higher probability of stale data.

    References Again Hibernate Doc

    I bet you haven't read through hibernate documentation itself, It has scenarios explaining them too :)

    Simple Explanation:With reference to persistent objects..

    Suppose a user has to update a form, you get the details of user in from through UserObject, This user object is persistent with session. Now if user doesn't submit the form, your session is open until server session expires, how long will you wait? If you have used getCurrentSession, another form request comes while previous one is not submitted, you have got dirty data now!! What if your object is waiting for a data that is to come for a web-service and it taking long enough, will you still keep session open, object persistent with session?

提交回复
热议问题