EclipseLink/Examples/JPA/AttributeGroup

From Eclipsepedia

< EclipseLink‎ | Examples‎ | JPA
Revision as of 01:07, 9 June 2010 by Douglas.clarke.oracle.com (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Starting with [[EclipseLink/Release/2.1.0|EclipseLink 2.1.0] EclipseLink has introduced the concept of an AttributeGroup that can be used configure the use of partial entities in fetch, load, copy, and merge operations. This example illustrates how this functionality can be used.

Contents

AttributeGroup Types and Operations

FetchGroup

LoadGroup

CopyGroup

The CopyGroup replaces the deprecated ObjectCopyPolicy being used to define how a entity is copied. In addition to specifying the attributes defining what should be copied from the source entity graph into the target copy the CopyGroup also allows definition of:

  • shouldResetPrimaryKey: Reset the identifier attributes to their default value. This is used when the copy operation is intended to clone the entity in order to make a new entity with similar state to the source. Default is false.
  • shouldRestVersion: Reset the optimistic version locking attribute to its default value in the copies. Default is false.
  • depth: defines cascade mode for handling relationships. By default CASCADE_PRIVATE_PARTS is used but it can also be configure to NO_CASCADE, CASCADE_ALL_PARTS, and CASCADE_TREE (which should be used if the attribute group's specified items are all that is to be copied).

Merging

When a partial entity is merged into a persistence context that has an AttributeGroup associated with it defining which attributes are available only those attributes are merged. The relationship mappings within the entity are still merged according to their cascade merge settings.

Usage Examples

Copy Examples

Here an Employee entity is copied with it basic names, address and phoneNumbers.

CopyGroup group = new CopyGroup();
group.cascadeTree(); // Only copy the specified attribute group items
group.addAttribute("firstName");
group.addAttribute("lastName");
group.addAttribute("address");
group.addAttribute("phoneNumbers");
 
Employee empCopy = (Employee) em.unwrap(JpaEntityManager.class).copy(emp, group);

Clone Entity using Copy and Persist

In this example an employee entity is cloned using a CopyGroup to copy all attributes with the exception of relationships (1:1, 1:M, M:M) that are not configured as private-owned. The resulting copy of the entity is then persisted to have new identity but the same state as its source.

CopyGroup group = new CopyGroup();
group.cascadePrivateParts(); // Copy all attributes and only private-owned relationships
group.setShouldResetPrimaryKey(true);
group.setShouldResetVersion(true);
 
Employee empCopy = (Employee) em.unwrap(JpaEntityManager.class).copy(emp, group);
System.out.println(">>> Employee copied");
 
// Persist the employee copy
em.persist(empCopy);