3.8.7.9.2. Foreign Keys

The org.apache.openjpa.persistence.jdbc.ForeignKey annotation represents a foreign key on the columns of a field. It is also used within the ContainerTable annotation to set a database foreign key on join columns. To set a constraint to the columns of a collection element, use the org.apache.openjpa.persistence.jdbc.ElementForeignKey annotation. These annotations have the following properties:

  • boolean enabled: Set this property to false to explicitly tell OpenJPA not to set a foreign key on these columns, when OpenJPA would otherwise do so.

  • String name: The name of the foreign key. OpenJPA will choose a name if you do not provide one, or will create an anonymous key.

  • boolean deferred: Whether to create a deferred key if supported by the database.

  • boolean implicit: Whether to mark a relation field value as implicitly referring to a related entity. This property can be used, for example, when a field value represents primary key field of a related entity, but for legacy or other logistic reasons, the field is declared as the same type of the primary key of the related entity instead of a reference to the entity itself. Hence no actual mapping can be defined on the field itself. If this implicit property is set, then no other property on the ForeignKey annotation can be set to their non-default value. This setting does not manifest as a database foreign key constraint.

  • ForeignKeyAction deleteAction: Value from the org.apache.openjpa.persistence.jdbc.ForeignKeyAction enum identifying the desired delete action. Defaults to RESTRICT.

  • ForeignKeyAction updateAction: Value from the org.apache.openjpa.persistence.jdbc.ForeignKeyAction enum identifying the desired update action. Defaults to RESTRICT.

Keep in mind that OpenJPA uses foreign key information at runtime to avoid constraint violations; it is important, therefore, that your mapping defaults and foreign key annotations combine to accurately reflect your existing database constraints, or that you configure OpenJPA to reflect on your database schema to discover existing foreign keys (see Schema Factory).