tags:

views:

55

answers:

3

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?

A: 

To be sure that accessor methods are used (like get... set.... is.... ). Thats part of the isolation principle.

Martin K.
But is there a technical requirement from JPA to enforce this (sometimes only pseudo) encapsulation?
deamon
It's API design. Many implementations deal with lazy proxies etc. Taking care of method access trees and subclasses is a lot easier than handle attribute access.
Martin K.
+2  A: 

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.

Cowan
there would be no way for proxying to work reliably << This is not right. (AOP..)
Martin K.
Agree with Martin K, bytecode enhancement also solves the problem - see other answer
DataNucleus
I should have been more clear, but I did say "no _simple_ way" later on. To a certain extent, the JPA spec is a 'lowest common denominator' between the different frameworks -- requiring frameworks to use AOP, or enhance the _calling_ class (as I gather DataNucleus does) would certainly be excessive for the JPA spec. Other persistence engines are, I guess, welcome to provide functionality BEYOND what JPA specifies, but to require field access interception for JPA spec compliance would be... onerous.
Cowan
A: 

With DataNucleus as JPA provider you could use public fields, but you would then need to mark any classes that access these fields as "persistence aware" (see the DataNucleus docs), so they can be enhanced to cater for this

DataNucleus