Show TOC

Native Databases with Foreign Key ConstraintsLocate this document in the navigation structure

Use

The SAP implementation of JPA does not require foreign key constraints on the database. Moreover, when you use the system database to store your application tables, you create the tables in the Java Dictionary and you use Open SQL connections to deploy them on the database. In this case you do not have foreign key constraints on the table definitions.

However, if you have a native database schema that imposes foreign key constraints, the JPA implementation has to sort the executed SQL statements in a way to avoid foreign key violations. You can enable this feature via the com.sap.jpa.execution.foreign-key-handling property and its value topological in the persistence.xml file.

More information: persistence.xml

JPA works with foreign key constraints on the database for the following scenarios:

  • Relationships without join-tables (one-to-one, many-to-one) - one foreign key constraint defined on the table of the entity that is the owning side of the relationship referring to the primary key of the table of the target entity

  • Relationships with join-tables (unidirectional one-to-many, many-to-many) - two foreign key constraints defined on the common join-table referring to the primary keys of the tables of the related entities

  • Secondary tables - one foreign key constraint defined on each secondary table referring to the primary key of the primary table

  • Inheritance - one foreign key constraint defined on each subclass table referring to the primary key of the superclass table

Note

In order JPA to work best, it is preferable that you use a database that does not impose foreign key constraints.

Caution
  • If the definition of the foreign key constraint has a CASCADE clause, the behavior of JPA is undefined.

  • If you have entities with an automatic primary key generator of the type IDENTITY , your application cannot work with foreign key constraints on the database.

    More information about IDENTITY generation strategy: Generated Primary Keys

            <property name = "com.sap.jpa.execution.foreign-key-handling" value = "topological"/>
         
Note

In rare cases, when a database model contains relationships that form a cycle, the changes performed on the persistence context can result in SQL statements that violate some referential constraint independently of their order. Consequently, the transaction fails and an exception is raised (for example, a RollbackException or a PersistenceException ). You can avoid this using NULL values for the foreign key column of the entity that is a part of a cyclic relationship. For example, if you want to INSERT such an entity, you can set its foreign key column to NULL and flush your changes. After the flush , you can replace the NULL value with the desired one.