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?
Entity PropertiesPersistability - An object is called persistent if it is stored in the database and can be accessed anytime. Persistent Identity - In Java, each entity is unique and represents as an object identity.
JPA needs a constructor and setter for each declared field. Does it mean we have to expose the default constructor and each setter ? JPA supports private constructor and private setters. This entity is a valid JPA entity and it can't be modified after its creation.
@Entity annotation defines that a class can be mapped to a table. And that is it, it is just a marker, like for example Serializable interface.
2. Entity. Entities in JPA are nothing but POJOs representing data that can be persisted to the database. An entity represents a table stored in a database.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With