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"/> ... </class>
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
column
s, foreign-key
s, and
index
es. The unique
element has the
following attributes:
name
: The constraint name. If left
unspecified, the JDOR implementation will choose a
suitable default or create an unnamed constraint.
deferred
: Set this attribute to
true
if this constraint's actions actions are
deferred. Deferred actions wait until just
before the database transaction commits before running.
This means the JDOR implementation doesn't have to worry about
ordering its SQL statements to meet constraints. Unfortunately,
many databases do not support deferred constraints.
The unique
element also allows nested
extension
elements.
Here is our previous example using a unique
element
instead of an attribute: