2

When creating an @Entity mapping a table my IDE notifies me: Persistent entity '*******' should have primary key.

But the table in the DB doesn't have an ID (I think it's bad but it's legacy which I've no permissions to fix)

What should I do? Will it work if I just omit the ID field? Or should I make up an ID which is not mapped on the table but satisfy the code?

J.J. Beam
  • 2,612
  • 2
  • 26
  • 55
  • 2
    I guess that you can still somehow uniquely identify a record, either by a single column or by multiple columns? Either way, put `@Id` on every column that is required to uniquely identify a record – XtremeBaumer Jun 20 '22 at 07:44
  • Just to add to @XtremeBaumer: The JPA ID annotation doesn't need to be on the table's primary key, it is just a convention as it is indexed and guaranteed to be unique. It should be unique, as it will be used for caching and object identity, so duplicates will cause a mess with what is returned from queries. IDs are also immutable; you cannot update the values and would have to delete and reinsert new instances to make changes to properties marked as IDs. – Chris Jun 20 '22 at 15:30

1 Answers1

0

Every JPA entity must have a primary key. You can find the documentation here.

From the Java Persistence book: Identity and Sequencing: here

If your object does not have an id, but its table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Try also to read the answers here

Oussama ZAGHDOUD
  • 1,767
  • 5
  • 15
  • ok, what should I do? I cannot edit the table – J.J. Beam Jun 20 '22 at 07:26
  • You can create another Table(clone) with an Id to be used with the JPA Entity , and within the DB you can manage the copy past between the two tables using some triggers for example.. – Oussama ZAGHDOUD Jun 20 '22 at 07:29
  • @J.J.Beam answer updated hope it will help – Oussama ZAGHDOUD Jun 20 '22 at 07:37
  • 2
    If the table does not provide an explicit id column, you can always annotate all fields with `@Id` effectively creating an composite primary key over all column. This way a record is unique by all fields, not just by an id column. That is in my opinion the better way – XtremeBaumer Jun 20 '22 at 07:40