JPA 2, The Access annotation
Join the DZone community and get the full member experience.
Join For FreeJPA 1 has a strict rule about what the access when defining your meta
annotations (you database to java mapping). In jpa 1 the standard was
the way the ID was mapped. So when you placed your @Id or @EmbeddedId annotation (which is mandatory for every bean annotated with the @Entity
annotation) on a field, all access will happen through the fields, when
you apply it on the getter/setter methods, all fields will use the
getter/setter methods.
JPA 2 adds some extra flexibility here. When you want your fields to be
access through the fields, but there is one field that you want to
modify when setting or getting, you can provide the @Access annotation.
This annotation defines the path of the persistence provider. It basicly has 2 modes
AccessType.FIELD, AccessType.PROPERTY;
You first have to annotate your Entity to set the base access mode, so the @Id rule is overruled.
@Entity @Access(AccessType.FIELD) public class Car implements Serializable { // some fields, getters and setters }
We have now configured the Pojo to use the fields unless we define it otherways.
by placing the @Access annotation on top of a getter (not setter, this
will give an error that the annotation only should be applied on
no-param methods), you tell it should use the getter/setter instead of
direct access to the field.
@Access(AccessType.PROPERTY) public Brand getBrand() { return brand; } public void setBrand(Brand brand) { this.brand = brand; }
Although the usefulness of this feature is definitely arguable, I do want to share this.
From http://styledideas.be/blog/2011/06/30/jpa-2-the-access-annotation/
Opinions expressed by DZone contributors are their own.
Comments