Why JPA requires Entity classes to be non-final & fields non-final

时间:2019-04-08 13:18:39

标签: jpa

Was reading about JPA here. Two of the requirements of an Entity class are that

  1. The class must not be declared final. No methods or persistent instance variables must be declared final.
  2. The class must have a public or protected, no-argument constructor.
  3. Persistent instance variables must be declared private, protected, or package-private.

Was curious to know why are these conditions required ?

2 个答案:

答案 0 :(得分:1)

  1. The class must not be declared final. No methods or persistent instance variables must be declared final.

JPA implementations use proxies in front of your entities to manage for example: Lazy loading. As a final class cannot be extended, a proxy cannot be built.

Some implementations as Hibernate can persist final classes but it can affect performance more info.

  1. The class must have a public or protected, no-argument constructor.

These kind of frameworks and others in order to create new objects use ```Class.newInstance()`` that is the reason why a no arg constructor is needed.

  1. Persistent instance variables must be declared private, protected, or package-private.

Being only accesible through accessor or business methods allow interception in proxies.

答案 1 :(得分:0)

The reasons are (at least some of them):

  1. JPA provider needs to create instances of the entity dynamically. If class would contain the only constructor which takes arbitrary arguments, JPA provider cannot figure out values for those arguments. That's why it must has a no-arg constructor.
  2. JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.
  3. Because you don't want access to the variables from outside directly, in order to keep encapsulation - this is an OOP reason. another reason is that many frameworks of persistence are having a getter/setter method to identify POJO "properties".
相关问题