Last week my colleague Albert Sikkema blogged about using UUIDs as primary keys. Interesting stuff, thanks again, Albert! This week I will continue the JPA implementation patterns series by discussing the relative merits of field access vs. property access.
The JPA specification allows two ways for the persistence provider to access the persistent state of an entity. The persistence provider can either invoke JavaBeans style property accessors (getters and setters) or access the instance fields of the entity directly. Which method is used depends on whether you have annotated the properties or the fields of an entity.
The JPA 1.0 specification does not allow you to mix access types within an entity or even an entity hierarchy. If you have annotated both fields and properties, the behaviour is undefined. The JPA 2.0 specification has the @Access annotation that makes it possible mix access types within an entity or entity hierarchy.
But the interesting question remains; which access type to use? A question that has been discussed before, but one I couldn't resist commenting on too.
Serializable id = ((HibernateProxy) entity).getHibernateLazyInitializer().getIdentifier()
It's nasty, but at least this code will be localized to where you really need it.
To summarize I think field access is the way to go because it offers better encapsulation (without it properly managing bidirectional associations is impossible) and the performance impact is negligible (#1 on the performance problems top 10 is still the interplay between the database and your Java app). The only downside are some snafu's in Hibernate's lazy loading implementation that require you to take extra care when using field access.
What access type do you prefer? Do you see any difference in the way field access and property access are implemented in JPA providers other than Hibernate? Please let me know by leaving a comment below. See you at the next JPA implementation patterns blog in which I will talk about mapping inheritance hierarchies in JPA.
For a list of all the JPA implementation pattern blogs, please refer to the JPA implementation patterns wrap-up.
Filed under Hibernate, JPA, JPA implementation patterns, Java, Performance | 1 Comment »
Field access. Property access is the interface that my entity exposes to the application, persistency is done on the fields. Those contain the data.