Field- vs. Property-Based access in JPA 📎
The new Java Persistence API specification allows Field-, as well as, Property Based access to the persistent state of an entity:
"...The persistent state of an entity is accessed by the persistence provider runtime[1] either via JavaBeans
style property accessors or via instance variables. A single access type (field or property access) applies
to an entity hierarchy. When annotations are used, the placement of the mapping annotations on either
the persistent fields or persistent properties of the entity class specifies the access type as being either
field- or property-based access respectively..." [ejb3 persistence spec]
You can choose the strategy by annotating either directly the (also private) members or the corresponding getters and setters. On the contrary to J2EE, entites are now objectoriented and polymorphic so known approaches like state encapsulation etc. are valid again. Because of evil getters and setters, direct field annotation should be preferred. This approach has some advantages:
- Only interesting fields are exposed to the outside world.
- The state is well encapsulated.
- You can declare getters and setters in interfaces, abstract classes or mapped superclasses, and override them in the concrete subclasses. It is easier to define transient contract.
There is only one drawback: the container does not use the getters and setters for value injection. The injection-process cannot be debugged with direct field injection....