Property Based Access in JPA - is an Emerging Antipattern

Thinking longer about property, vs field based access, I cannot imagine a reasonable use case for the property based annotation. It is much cleaner to hide the internal, also persistent, state and expose only business methods (instead of dumb getters/setters).
So you should use:

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID")
    private Long id;

instead of:

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID")
    public Long getId(){return this.id;}

The field-based injection clearly separates between the business logic and state and promotes encapsulation.
And remember, Getters/Setters are evil, but sometimes necessary (e.g. if you like to use detached objects as Value Objects).


Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

I actually agree. In fact, as we move more and more towards this end, why have getters and setters when all we really want is just a data structure, meaning, we just need something to pass around in our language/platform. Do we really need to have behaviour in these data objects? Personally, I have been moving towards externalizing all "logic" so that what goes from the front to the back is the equivalent of structs.

Posted by Jin Chun on November 17, 2006 at 03:56 PM CET #

There's a functional difference at least for Hibernate (See Page 564 in "Java Persistence with Hibernate"). Hibernate allows to invoke the identifier getter method on a proxied object without hitting the database but only when the annotations are placed on the accessors (whereas the object will be initialized from the database when the annotation is put on the field). So in terms of efficiency it might be better to put it on the accessors.

Posted by Stefan Krause on November 16, 2007 at 12:29 PM CET #

I prefer field based access as well. It provides more flexibility than the property-based access and also I can view all the fields together and have a complete understanding of the mappings.

rk
http://www.RentalAndRealEstate.com

Posted by rk on February 12, 2008 at 04:28 AM CET #

I beg to differ. Property based annotation allows shielding of the value so only limited relevant functions will be able to access it's value or do changes, so limitting chances of mistake. It's dumb, yes. But it's the extra protection.

Posted by HDB For Rent on June 25, 2008 at 08:08 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License