12.2. 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 EJB persistence, you represent other unique constraints with an array of UniqueConstraint annotations within the table annotation. The unique constraints you define 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 transaction, you remove an object A and persist a new object B, both with the same F value. The EJB persistence runtime must ensure that the SQL deleting A is sent to the database before the SQL inserting B to avoid a unique constraint violation.

UniqueConstraint has a single property:

In XML, unique constraints are represented by nesting unique-constraint elements within the table element. Each unique-constraint element in turn nests column-name text elements to enumerate the contraint's columns.

Example 12.2. Defining a Unique Constraint

The following defines a unique constraint on the TITLE column of the ART table:

@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
public class Article

The same metadata expressed in XML form:

<entity class="org.mag.Article">
    <table name="ART">


Skip navigation bar   Back to Top