2

In JPA project, when I generate tables for entities I can't see any table foreign key constraints created on database side.

I concluded that JPA cannot create table foreign key constraints in database and that referential integrity is enforced in JPA (on application side) and not by database.

Can someone confirm if this is so?

sasha
  • 93
  • 1
  • 2
  • 7
  • 2
    No, it's not. It is definitely the database job to enforce referential integrity. But it's normally not JPA's job to design, create and maintain your database schema. Some JPA engines allow creating a schema, and that can be useful to quickly start. And the one I'm using (Hibernate) does create foreign key constraints. – JB Nizet Dec 02 '18 at 13:14
  • I use Eclipselink 2.7 (so JPA 2.1) with HanaDB (I use Generic JDBC profile with Hana driver), I see no Table foreign key constraints generated in sql. – sasha Dec 02 '18 at 15:45
  • So tag your question as EclipseLink then. DataNucleus also creates FKs when requested to. Since you dont post any config then its a bit moot arguing the toss over what is "right" –  Dec 02 '18 at 15:48
  • Then tag your questions with the relevant tags, because EclipseLink is not the most popular JPA engine, and I haven't even heard of HanaDB. So if you want specialists of these two things to see your question, you'd better tag it correctly. – JB Nizet Dec 02 '18 at 15:48
  • BillyFrost and JB Nizet I should have better tagged the question as you said. There are no examples because I wanted answer in general is JPA supposed to create Table constraints on DB side or not. It seems it's JPA provider specific and that EclipseLink does not support it. – sasha Dec 02 '18 at 17:28
  • Show the settings you are using for EclipseLink. It works on many DBs, so it likely comes down to your DB platform class or settings. The HANNAPlatform DatabasePlatform subclass returns false for supportsForeignKeyConstraints, so you may have to write your own constraint handling for this DB. – Chris Dec 02 '18 at 21:51

1 Answers1

1

According to the JPA 2.2 specification, the persistence manager should create foreign key constraints. For example in the case of a one-to-one mapping:

Assuming that:

  • Entity A references a single instance of Entity B.

  • Entity B references a single instance of Entity A.

  • Entity A is specified as the owner of the relationship.

The following mapping defaults apply:

  • Entity A is mapped to a table named A.

  • Entity B is mapped to a table named B.

  • Table A contains a foreign key to table B. The foreign key column name is formed as the concatenation of the following: the name of the relationship property or field of entity A; the name of the primary key column in table B. The foreign key column has the same type as the primary key of table B and there is a unique key constraint on it.

Community
  • 1
  • 1
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240