15.14. Unique Constraints

Unique constraints ensure that the data in a column or combination of columns is unique for each row. A table's primary key, for example, functions as an implicit unique constraint. In JDOR, you represent other unique constraints with the unique attribute or the unique element. These attributes and elements are used during table creation to generate the proper database constraints, and may also be used at runtime to order INSERT, UPDATE, and DELETE statements. For example, suppose there is a unique constraint on the columns of field F. In the same JDO transaction, you delete an object A and make persistent a new object B, both with the same F value. The JDOR runtime must ensure that the SQL deleting A is sent to the database before the SQL inserting B to avoid a unique constraint violation.

The unique attribute can be either true or false. When placed on a mapping element, it applies to all columns of that element. The following elements accept the unique attribute: field, join, element, key, value.

Example 15.34. Using the unique Attribute

The following adds a unique constraint to the columns of the Article.title field:

<class name="Article" table="ART">
    <field name="title" column="TITLE" unique="true"/>

The contextual unique element serves the same purpose as the unique attribute, but allows you to specify more information about the constraint. Any element that accepts the unique attribute also accepts a nested unique element. The element goes after any nested columns, foreign-keys, and indexes. The unique element has the following attributes:

The unique element also allows nested extension elements.

Here is our previous example using a unique element instead of an attribute:

Example 15.35. Using Contextual Unique Elements

<class name="Article" table="ART">
    <field name="title" column="TITLE">
        <unique name="ART_TTL_UNQ"/>


Skip navigation bar   Back to Top