Note that you do not need to create a new session and log in before every transaction. The recommended pattern is to acquire a client session per client access (or thread), and then acquire the necessary unit of work from this client session.

The unit of work is valid until the commit or release method is called. After a commit or release transaction, a unit of work is not valid even if the transaction fails and is rolled back.

114.2 Creating an Object

When you create new objects in the unit of work, use the registerObject method to ensure that the unit of work writes the objects to the database at commit time.

The unit of work calculates commit order using foreign key information from one-to-one and one-to-many mappings. If you encounter constraint problems during a commit transaction, verify your mapping definitions. The order in which you register objects with the registerObject method does not affect the commit order.

Example 114-1 and Example 114-2 show how to create and persist a simple object (without relationships) using the clone returned by the unit of work registerObject method.

Example 114-1 is preferred: it gets you into the pattern of working with clones and provides the most flexibility for future code changes. Working with combinations of new objects and clones can lead to confusion and unwanted results.

114.3 Modifying an Object

In Example 114-3, a Pet is read prior to a unit of work: the variable pet is the cache copy clone for that Pet. Inside the unit of work, register the cache copy to get a working copy clone. You then modify the working copy clone and commit the unit of work.

Example 114-4 shows how to take advantage of the fact that you can query through a unit of work and get back clones, saving the registration step. However, the drawback is that we do not have a handle to the cache copy clone.

If you wanted to do something with the updated Pet after the commit transaction, you would have to query the session to get it (remember that after a unit of work is committed, its clones are invalid and should not be used).

Take care when querying through a unit of work. All objects read in the query are registered in the unit of work and therefore will be checked for changes at commit time. Rather than do a ReadAllQuery through a unit of work, it is better for performance to design your application to do the ReadAllQuery through a session, and then register in a unit of work only the objects that need to be changed.

114.4 Associating a New Target to an Existing Source Object

This section explains how you can associate a new target to an existing source object, including the following:

Deciding which approach to use depends on whether or not your code requires a reference to the cache copy clone of the new object after the unit of work is committed, and on how adaptable to change you want your code to be.

114.4.1 How to Associate a New Target to an Existing Source Object in a Unidirectional Relationship: Reference to the New Cache Object After Commit not Required

Example 114-5 shows how to associate a new target with an existing source in a unidirectional relationship without retaining a reference to the cache object.

When the Pet object is read using the unit of work, TopLink automatically registers it. Because there is a unidirectional relationship between the Pet object and the new PetOwner and VetVisit objects, you do not need to register the new PetOwner or VetVisit objects. TopLink can reach these new objects through the registered Pet object and automatically detect that they are new objects.

114.4.2 How to Associate a New Target to an Existing Source Object in a Unidirectional Relationship: Reference to the New Cache Object After Commit Required

Example 114-6 shows how to associate a new target with an existing source in a unidirectional relationship and retain a reference to the cache object.

When the Pet object is read using the unit of work, TopLink automatically registers it. Because there is a unidirectional relationship between the Pet object and the new PetOwner and VetVisit objects, you do not need to register the new PetOwner or VetVisit objects. TopLink can reach these new objects through the registered Pet object and automatically detect that they are new objects.

However, by using UnitOfWork method registerObject, you can retain a handle to the post-commit cache objects in case your code needs to continue using them after commit: for example, to display their new contents in a GUI.

Example 114-8 shows how to register a new object when a bidirectional relationship exists such as that between manager and employee.

Because Employee method setManager modifies the Employee you pass in (as Example 114-7 shows), you must pass in managerClone that registerObject returns.

After you call setManager, you establish the bidirectional relationship between newEmployee and managerClone. Because newEmployee is reachable from the manager object already registered with the unit of work, TopLink can automatically detect that it is a new object. Consequently, you do not need to register newEmployee at all and it is, in fact, an error to call registerObject on newEmployee in this case.

If you need the cache object after the unit of work commit transaction, in this case, you must query for it.

Example 114-8 Resolving Issues When Adding New Objects

// Get an employee read from the parent session of the unit of work
Employee manager = (Employee)session.readObject(Employee.class);
// Acquire a unit of work
UnitOfWork uow = session.acquireUnitOfWork();
// Register the manager to get its clone
Employee managerClone = (Employee)uow.registerObject(manager);
// Create a new employee
Employee newEmployee = new Employee();
newEmployee.setFirstName("Spike");
newEmployee.setLastName("Robertson");
/* INCORRECT: Do not associate the new employee with the original manager. Thiswill cause a QueryException when TopLink detects this error during commit *///newEmployee.setManager(manager);/* CORRECT: Associate the new object with the clone. Note that in this example, the setManager method is maintaining the bidirectional managedEmployees relationship and adding the new employee to its managedEmployees. At commit time, the unit of work will detect that this is a new object and will take the appropriate action */
newEmployee.setManager(managerClone);
/* INCORRECT: Do not register the newEmployee: this will create two copies and cause a QueryException when TopLink detects this error during commit *///uow.registerObject(newEmployee);// Commit the unit of work
uow.commit();

Example 114-8 shows how to register a new object when a bidirectional relationship exists such as that between manager and employee.

Example 114-10 Resolving Issues When Adding New Objects

// Get an employee read from the parent session of the unit of work
Employee manager = (Employee)session.readObject(Employee.class);
// Acquire a unit of work
UnitOfWork uow = session.acquireUnitOfWork();
// Register the manager to get its clone
Employee managerClone = (Employee)uow.registerObject(manager);
// Create a new employee
Employee newEmployee = new Employee();
newEmployee.setFirstName("Spike");
newEmployee.setLastName("Robertson");
/* INCORRECT: Do not associate the new employee with the original manager. Thiswill cause a QueryException when TopLink detects this error during commit *///newEmployee.setManager(manager);/* CORRECT: Associate the new object with the clone. Note that in this example, the setManager method is maintaining the bidirectional managedEmployees relationship and adding the new employee to its managedEmployees. At commit time, the unit of work will detect that this is a new object and will take the appropriate action */
newEmployee.setManager(managerClone);
/* INCORRECT: Do not register the newEmployee: this will create two copies and cause a QueryException when TopLink detects this error during commit *///uow.registerObject(newEmployee);/* CORRECT: In the above setManager call, if the managerClone's managedEmployees was notmaintained by the setManager method, then you should call registerObject before the new employee is related to the manager. If in doubt, you could use the registerNewObject method to ensure that the newEmployee is registered in the unit of work. The registerNewObject method registers the object, but does not make a clone */
uow.registerNewObject(newEmployee);
// Commit the unit of work
uow.commit();

Because Employee method setManager modifies the Employee you pass in (as Example 114-7 shows), you must pass in managerClone that registerObject returns.

After you call setManager, you establish the bidirectional relationship between newEmployee and managerClone. Because newEmployee is reachable from the manager object already registered with the unit of work, TopLink can automatically detect that it is a new object. Consequently, you do not need to register newEmployee at all and it is, in fact, an error to call registerObject on newEmployee in this case.

If your code must be able to query for the new child object prior to commit, register the new object using UnitOfWork method registerNewObject. Unlike registerObject, this method does not create a clone.

Another difference between registerNewObject and registerObject is that registerNewObject does not cascade registration to child objects. If you call registerNewObject on a parent object, you must also call registerNewObject on new child instances if your code must be able to query for the new child object prior to commit and you prefer not to use conforming queries.

If you need the cache object after the unit of work commit transaction, you must query for it.

114.5 Associating a New Source to an Existing Target Object

This section describes how to associate a new source object with an existing target object with one-to-many and one-to-one relationships.

TopLink follows all relationships of all registered objects (deeply) in a unit of work to calculate what is new and what has changed. This is known as persistence by reachablity. In Section 114.4, "Associating a New Target to an Existing Source Object", we saw that when you associate a new target with an existing source, you can choose to register the object or not. If you do not register the new object, it is still reachable from the source object (which is a clone, hence it is registered). However, when you need to associate a new source object with an existing target, you must register the new object. If you do not register the new object, then it is not reachable in the unit of work, and TopLink will not write it to the database.

For example, the code shown in Example 114-11 shows how to create a new Pet and associate it with an existing PetOwner.

In this situation, you should register the new object and work with the working copy of the new object. If you associate the new object with the PetOwner clone without registering, it will not be written to the database.

If you fail to register the clone and accidentally associate the cache version of the existing object with the new object, then TopLink will generate an error which states that you have associated the cache version of an object ("from a parent session") with a clone from this unit of work. You must work with working copies in units of work.

The most common error when associating existing objects is failing to work with the working copies. If you accidentally associate a cache version of an object with a working copy you will get an error at commit time indicating that you associated an object from a parent session (the cache version) with a clone from this unit of work.

Example 114-13 shows another example of associating an existing source to an existing target object.

Example 114-13 Associating Existing Objects

// Get an employee read from the parent session of the unit of work
Employee employee = (Employee)session.readObject(Employee.class)
// Acquire a unit of work
UnitOfWork uow = session.acquireUnitOfWork();
Project project = (Project) uow.readObject(Project.class);
/* When associating an existing object (read from the session) with a clone, we must make sure we register the existing object and assign its clone into a unit of work *//* INCORRECT: Cannot associate an existing object with a unit of work clone. A QueryException will be thrown *///project.setTeamLeader(employee);/* CORRECT: Instead register the existing object then associate the clone */
Employee employeeClone = (Employee)uow.registerObject(employee);
project.setTeamLeader(employeeClone);
uow.commit();

114.7 Deleting Objects

To delete objects in a unit of work, use the deleteObject or deleteAllObjects method. When you delete an object that is not already registered in the unit of work, the unit of work registers the object automatically.

When you delete an object, TopLink deletes the object's privately owned child parts, because those parts cannot exist without the owning (parent) object. At commit time, the unit of work generates SQL to delete the objects, taking database constraints into account.

114.7.1 How to Use the privateOwnedRelationship Attribute

Relational databases do not have garbage collection like a Java Virtual Machine (JVM) does. To delete an object in Java you just remove the reference to the object. To delete a row in a relational database, you must explicitly delete it. Rather than tediously manage when to delete data in the relational database, use the mapping attribute privateOwnedRelationship to have TopLink manage the garbage collection in the relational database for you.

As shown in Example 114-14, when you create a mapping using Java, use its privateOwnedRelationship method to tell TopLink that the referenced object is privately owned: that is, the referenced child object cannot exist without the parent object.

When you create a mapping using TopLink Workbench, you can select the Private Owned check box under the General tab.

When you tell TopLink that a relationship is privately owned, you are specifying the following:

If the source of a privately owned relationship is deleted, then delete the target.

If you remove the reference to a target from a source, then delete the target.

Do not configure privately owned relationships to objects that might be shared. An object should not be the target in more than one relationship if it is the target in a privately owned relationship.

The exception to this rule is the case when you have a many-to-many relationship in which a relation object is mapped to a relation table and is referenced through a one-to-many relationship by both the source and the target. In this case, if the one-to-many mapping is configured as privately owned, then when you delete the source, all the association objects will be deleted.

// If the Pet-PetOwner relationship is privateOwned// then the PetOwner will be deleted at uow.commit()// otherwise, just the foreign key from PET to PETOWNER will// be set to null. The same is true for VetVisit
UnitOfWork uow = session.acquireUnitOfWork();
Pet petClone = (Pet)uow.readObject(Pet.class);
petClone.setPetOwner(null);
VetVisit vvClone =
(VetVisit)petClone.getVetVisits().get(0);
vvClone.setPet(null);
petClone.getVetVisits().remove(vvClone);
uow.commit();

If the relationships from Pet to PetOwner and from Pet to VetVisit are not privately owned, this code produces the following SQL:

114.7.2 How to Explicitly Delete from the Database

If there are cases where you have objects that will not be garbage collected through privately owned relationships (especially root objects in your object model), then you can explicitly tell TopLink to delete the row representing the object using the deleteObject API, as shown in Example 114-16.

114.7.3 What You May Need to Know About the Order in which Objects Are Deleted

The unit of work does not track changes or the order of operations. It is intended to insulate you from having to modify your objects in the order the database requires.

By default, at commit time, the unit of work correctly puts in order all insert and update operations using the constraints defined by your schema. After all insert and update operations are done, the unit of work will issue the necessary delete operations.