Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 573
deamon Avatar asked Jan 11 '10 09:01

deamon


People also ask

What are the JPA entity properties?

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.

Do JPA entities need setters?

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.

What does @entity annotation mean?

@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.

What does @entity mean in JPA?

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.


2 Answers

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.

like image 142
Cowan Avatar answered Oct 29 '22 02:10

Cowan


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

like image 36
DataNucleus Avatar answered Oct 29 '22 03:10

DataNucleus