Over a million developers have joined DZone.

JPA 2.0: Why AccessType is Relevant

· 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.

It has long been debated whether field access is superior to property access for JPA entities. Most arguments that I've seen hinge on performance versus encapsulation. While these arguments may be interesting from a theoretical perspective, control over field access is in fact very useful in solving real-world problems.

Field access allows code to distinguish between the JPA provider setting properties while loading an entity versus application code setting a property.

This was very useful for a project that I'm involved with that has de-normalized data or other fields that are computed and persisted. Here's how it works:

  • In the setter for various properties that affect the computation of a de-normalized property, the value of the de-normalized property is set to null. @AccessType(FIELD) is used for these properties.
  • In the getter for the de-normalized property, if the value is null the de-normalized value is recomputed.
  • In a @PrePersist method, the getter is called to ensure that the de-normalized value is properly persisted.

 

Using this technique maintaining de-normalized data becomes simple and robust.

While this feature has been available within Hibernate since 3.0, I'm glad to see that JPA 2.0 (JSR 317) introduces a standard annotation to control this behaviour.

From http://greensopinion.blogspot.com

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 }}