Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't entity class in JPA be final?

Tags:

java

jpa

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 declared final.

What is the reason? Is JPA subclassing the entity classes and redefining the methods?

like image 468
Karel Bílek Avatar asked Aug 12 '10 22:08

Karel Bílek


People also ask

Can we make entity class as final?

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.

What in JPA Cannot contain final fields or methods while mapping?

JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.

How entity class is defined in JPA?

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.

What impact does making an entity bean final in Hibernate?

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.


1 Answers

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.

like image 90
Jose Diaz Avatar answered Sep 18 '22 20:09

Jose Diaz