Adam Bien's Weblog

Thursday Nov 16, 2006

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


[my tweets]  Rss My book: Real World Java EE - Rethinking Best Practices

Interviews/About
My Recent Book
Java One 2009
CommunityOne East N.Y.C
JavaONE 2008 Interview
Search
...the last 150 posts
...the last 10 comments
greenfire.dev.java.net
Links
my.netbeans.org
Visitors
License