JPA 2, The Access annotation

JPA 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. :-)

3 thoughts on “JPA 2, The Access annotation

  1. Pingback: JPA 2 – Entity extends abastract non-entity | Coisas de software

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>