Over a million developers have joined DZone.

JPA 2, The Access annotation

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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

 

From http://styledideas.be/blog/2011/06/30/jpa-2-the-access-annotation/

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}