Oracle TopLink Developer's Guide
10g Release 3 (10.1.3) B13593-01 |
|
Previous |
Next |
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 101-1 and Example 101-2 show how to create and persist a simple object (without relationships) using the clone returned by the unit of work registerObject
method.
Example 101-1 Creating an Object: Preferred Method
UnitOfWork uow = session.acquireUnitOfWork(); Pet pet = new Pet(); Pet petClone = (Pet)uow.registerObject(pet); petClone.setId(100); petClone.setName("Fluffy"); petClone.setType("Cat"); uow.commit();
Example 101-2 shows a common alternative.
Example 101-2 Creating an Object: Alternative Method
UnitOfWork uow = session.acquireUnitOfWork(); Pet pet = new Pet(); pet.setId(100); pet.setName("Fluffy"); pet.setType("Cat"); uow.registerObject(pet); uow.commit();
Both approaches produce the following SQL:
INSERT INTO PET (ID, NAME, TYPE, PET_OWN_ID) VALUES (100, 'Fluffy', 'Cat', NULL)
Example 101-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.