Detached Entity Objects

Detached entity objects are objects in special state in which they are not managed by any EntityManager but still represent objects in the database.Compared to managed entity objects,detached objects are limited in functionality:

1. Many JPA methods do not accept detached objects (e.g. lock)

2. Retrieval by navigation from detached objects is not supported ,so only persistent fields that have been loaded before detachment should be used.

3. Changes to detached entity objects are not stored in the database unless modified detached objects are merged back into an EntityMananger to become managed again.

Detached objects are useful in situations in which an EntityMananger is not available and for transferring objects between different EntityManager instances.

一; Explicit(明确地)Detach

When a managed entity objects is serialized and then deserialized ,the deserialized entity object (but not the original serialized object) is constructed as detached entity object since is not associated with any EntityManager.

In addition,in JPA 2 we can detach an entity object by using the detach method:

em.detach(employee);
View Code

An IllegalArgumentException is thrown by detach if the arguments is not an entity object.

二; Cascading Detach

Marking a reference field with CascadeType.DETACH(or CascadeType.ALL,which includes DETACH) indicates that detach operations should be cascaded automcatically to entity objects that  are referenced by that field (multiple entity obejct can be referenced by a collection field):

1 @Entity
2 class Employee {
3      :
4     @OneToOne(cascade=CascadeType.DETACH)
5     private Address address;
6      :
7 }
View Code

In the example above, the Employee entity class contains an address field that references an instance of Address, which is another entity class. Due to the CascadeType.DETACH setting, when an Employee instance is detached the operation is automatically cascaded to the referenced Address instance, which is then automatically detached as well. Cascading may continue recursively when applicable (e.g. to entity objects that the Address object references, if any).

三; Bulk Detach

The following operations clear the entire EntityManager's persistence context and detach all managed entity objects:

  • Invocation of the close method, which closes an EntityManager.
  • Invocation of the clear method, which clears an EntityManager's persistence context.
  • Rolling back a transaction - either by invocation of rollback or by a commit failure.
posted @ 2016-04-29 15:40  Jacky312  阅读(205)  评论(0编辑  收藏  举报