Skip to main content

Unique Constraints

Often, it is necessary to prevent users from creating instances with duplicate values. There might be some fields that are used as keys to uniquely identify an instance. Or perhaps you might want to prevent wild growth of data.

To enforce this, each DataElement can have one or more UniqueConstraints.

Each one lists a number of Fields. The constraint will generate a check to make sure it is not possible to create 2 instances with the same values for these Fields.

Document.xml
<dataElement name="Document">
<fields>
<field name="name">
<!-- ... -->
</field>
</fields>
<uniqueConstraints>
<uniqueConstraint>
<fields>
<field component="documents" dataElement="Document" name="name"/>
</fields>
</uniqueConstraint>
</uniqueConstraints>
</dataElement>

UniqueKey option

UniqueConstraints replace the option uniqueKey and improve on it:

  • You can have more than one UniqueConstraints
  • The check uses a dedicated query instead of a Finder, so that it will work even for null values.
  • No need to explicitly define a Finder
  • No more loosely typed String to define the Fields
Option
uniqueKey DeprecatedDataElement
Deprecated

Use UniqueConstraints instead.

Adds a validation that checks for any duplicates based on the provided set of Fields.

The field name or list of field names provided as the option value determine the unique key of the DataElement. When specifying a list of field names, these should be separated by underscores.

It will reject any new instances that has the same values for these Fields as an instance that already exists in the database. Likewise, it will also prevent any updates that would create a collision with another instance.

The uniqueness is enforced at the logic level. A {DataElement}UniquenessValidation class is generated which exposes a checkUnique method. Internally, a finder using the combination of the provided fields is then used to retrieve already existing instances. If a finder artifact for the combination of fields does not exist in the model, it will be automatically generated and added to the model. The checkUnique() method is invoked by the create and modify methods of the {DataElement}Bean.

<options>
<uniqueKey>name_version</uniqueKey>
</options>