Skip Headers

# Creating an Object

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: Creating an Object: Preferred Method and Example: Creating an Object: Alternative Method show how to create and persist a simple object (without relationships) using the clone returned by the unit of work `registerObject` method.

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: Creating an Object: Alternative Method shows a common alternative.

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: Creating an Object: Preferred Method 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.