Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JPA 2, The Access annotation

DZone's Guide to

JPA 2, The Access annotation

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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/

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}