Why can't an entity class in JPA be final or have a final methods? Citing from here -
An entity class must follow these requirements:
...
The class must not be declared
final
. No methods or persistent instance variables must be declaredfinal
.
What is the reason? Is JPA subclassing the entity classes and redefining the methods?
The entity class must not be final. No methods or persistent instance variables of the entity class may be final. If an entity instance is to be used remotely as a detached object, the entity class must implement the Serializable interface. Both abstract and concrete classes can be entities.
JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.
To transform this class into an entity add @Entity and @Id annotation in it. @Entity - This is a marker annotation which indicates that this class is an entity. This annotation must be placed on the class name. @Id - This annotation is placed on a specific field that holds the persistent identifying properties.
In short, making a JPA Entity or Hibernate Persistence class final, limits the ability of Hibernate to use Proxies, which in turn prevents Hibernate from applying some performance optimizations.
By definition, an entity is a class that can be persisted to a database, so having a final field would make no sense in the context of something that will end up being a record in your database. The requirement of no final class and no final methods has to do with the way in which JPA implementations actually deal with persisting instances of your entities classes.
It is common for implementations to subclass your class at runtime and/or add byte code dynamically to your classes, in order to detect when a change to an entity object has occurred. If your class is declared as final, then that would not be possible.
There is of course a lot more reasons than just those, here is an article that gives more information of how ORM in general work behind the covers, that might help you better understand the other requirements for JPA entities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With