Search code examples
javajpajakarta-ee

Why is "public" not allowed for properties in JPA entities?


The JPA 2.0 specification says on page 22:

The instance variables of a class must be private, protected, or package visibility independent of whether field access or property access is used. When property access is used, the property accessor methods must be public or protected.

Why isn't public access allowed?


Solution

  • With public fields, there would be no way for proxying to work reliably -- if someone accesses a field directly, then there is no simple way for the persistence framework to intercept that call and (say) initialize the containing object, if it's a proxy.

    If field access is not possible, synthetic getter methods can be generated on the proxy object to intercept the method calls and do any required 'behind-the-scenes' work.