1

A lot of JPA entity demo classes have the following snippets:

 @Id
 private Long id;

Can anyone see any drawbacks to always marking the id property as final?

 @Id
 private final Long id;

It seems like we almost always want to do this in order to preserve the entities identity.

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

3

Short answer

It makes using the JPA class impossible.

Elaboration

final is a Java keyword, not a framework keyword. Java doesn't care what the contract for a JPA entity is. You cannot declare a final field that is not uninitialized, since, by contract, a final field can be written only once.

Also, it is not true that ID properties are immutable. For starters, they change when an object is serialized - a null ID is replaced by a generated ID. Less trivially, when an entity is deleted from a database, its ID is nullified.

Ole
  • 41,793
  • 59
  • 191
  • 359
Piotr Wilkin
  • 3,446
  • 10
  • 18
  • Hmmm - Initially I was thinking that it could be initialized in the constructor (So no database assigned key) - but IIUC JPA requires an empty constructor so the field cannot be initialized during onstruction right? – Ole Oct 20 '17 at 22:44
  • 1
    Yes, and also that is generally not how you persist objects using JPA. You first fill in the entity and then persist it (thus giving it a database ID). A JPA entity can live perfectly well in an unpersisted state, as a POJO. – Piotr Wilkin Oct 20 '17 at 22:46
  • True - Trying to figure out the fastest simplest way to implement equals and hashcode - and if we can assign the primary key upfront and never change it - then we can base equals and hashcode on it - Asked about it for Kotlin earlier - https://stackoverflow.com/questions/46838256/extending-the-kotlin-data-class-for-use-with-jpa - Lombok has annotations in this space as well. – Ole Oct 20 '17 at 22:51
  • So basically the drawback is that it makes using the JPA class impossible :) ? – Ole Oct 20 '17 at 22:58
  • In a nutshell, yes :> – Piotr Wilkin Oct 20 '17 at 22:59
  • That settles that :) – Ole Oct 20 '17 at 23:01