简体   繁体   中英

Why can't entity class in JPA be final?

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?

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.

Because persistence providers make proxies of objects. These proxies are creating runtime subclasses of the entities/classes and also might be adding some flags to identify whether there is a change in the data. so that is why your class should not be final to have the ability to change it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM