Products
Technologies

Developer resources

Persist a new entity instance in CF ORM when the PK property is not a null or empty string, or the class is passed in from Flex Remoting.

Not yet rated.

Problem

You have a new entity instance that needs inserted into the database with CF ORM. If the PK property is a non-null or not an empty string, CF ORM will assume it's an updated entity rather than a new instance and try to update a database record rather than insert a new record.

Solution

Use the unsavedValue attribute of the cfproperty tag for the id field to let CF ORM know what value considers the instance as a new instance rather than an updated one.

Detailed explanation

A common situation in which you might run into this problem is when using CF ORM to persist entities passed in from Flex Remoting.

By default, if the entity's primary key property is null or an empty string, CF ORM will attempt to insert it. If the primary key property has a value, CF ORM will look for an existing record with the same primary key to update.

When the class is instantiated in ActionScript, the integer property will default to 0. When it is passed to CF to be persisted, CF ORM will recognize the 0 value as a valid PK value and attempt to update a record when the intention was to insert a new record. In this scenario, any object that maps its primary key to an auto-incremented integer will be viewed as an existing entity when its primary key is defaulted to 0 on creation in Actionscript.

To get around this problem, make use of the unsavedValue attribute of the primary key property to let CF ORM know what value constitutes this entity as unsaved.

<cfproperty name="userId" fieldtype="id" unsavedValue="0">

In addition, you can utilize the default attribute on the cfproperty so that anytime a new entity is instantiated in CF it can default to the same value as the Actionscript equivelant. Having the entity instantiation process the same means you can leverage the same persistance logic regardless of whether the object was instantiated in CF or Actionscript.

<cfproperty name="userId" fieldtype="id" unsavedValue="0" default="0">


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes