5.1.19. key

5.1.19. key

We've seen the <key> element crop up a few times now. It appears anywhere the parent mapping element defines a join to a new table, and defines the foreign key in the joined table, that references the primary key of the original table.

<key
        column="columnname"
        on-delete="noaction|cascade"
        property-ref="propertyName"
        not-null="true|false"
        update="true|false"
        unique="true|false"
/>

column (optional): The name of the foreign key column. This may also be specified by nested <column> element(s).

on-delete (optional, defaults to noaction): Specifies whether the foreign key constraint has database-level cascade delete enabled.

property-ref (optional): Specifies that the foreign key refers to columns that are not the primary key of the orginal table. (Provided for legacy data.)

not-null (optional): Specifies that the foreign key columns are not nullable (this is implied whenever the foreign key is also part of the primary key).

update (optional): Specifies that the foreign key should never be updated (this is implied whenever the foreign key is also part of the primary key).

unique (optional): Specifies that the foreign key should have a unique constraint (this is implied whenever the foreign key is also the primary key).

We recommend that for systems where delete performance is important, all keys should be defined on-delete="cascade", and Hibernate will use a database-level ON CASCADE DELETE constraint, instead of many individual DELETE statements. Be aware that this feature bypasses Hibernate's usual optimistic locking strategy for versioned data.

The not-null and update attributes are useful when mapping a unidirectional one to many association. If you map a unidirectional one to many to a non-nullable foreign key, you must declare the key column using <key not-null="true">.