Apache Cayenne > Index > Cayenne FAQ > Setting Initial Values
Added by Michael Gentry, last edited by Ari Maniatis on Oct 04, 2007  (view change)
Note
This advice is applicable to Cayenne before version 3. After that, use lifecycle events for a more satisfying experience.

Sometimes you need to create a new object in Cayenne with default values. This is especially true if you are using Cayenne's entity inheritance feature, since you need to use one or more columns with marker values which indicate which class the object represents (using the Qualifier field under the Entity tab for an ObjEntity).

When you create an object entity using dataContext.createAndRegisterNewObject(ObjEntity.class) (or similar), the best place to set default/initial values in the newly created object is in the setPersistenceState(int state) method. Edit your object entity subclass (created by Cayenne Modeler) to include the following:

SomeObjEntity.java
import org.objectstyle.cayenne.PersistenceState;

public class SomeObjEntity extends _SomeObjEntity
{
  public void setPersistenceState(int state)
  {
    super.setPersistenceState(state);
    
    // if the object was just created, set initial values
    if (state == PersistenceState.NEW)
    {
       // Set all initial values here
    }
  }
}