Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations: methods vs variables

I was always sure (don't know why) that it's better to add annotations to variables, but while browsing the Hibernate doc http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection I noticed they tend to annotate the methods. So should I put my annotations before methods, like this:

@Entity
public class Flight implements Serializable {
private long id;

@Id @GeneratedValue
public long getId() { return id; }

public void setId(long id) { this.id = id; }
}  

Or is it better to do it like this:

@Entity
public class Flight implements Serializable {
@Id @GeneratedValue
private long id;

public long getId() { return id; }

public void setId(long id) { this.id = id; }
}  

Or maybe there's no difference?

like image 282
Mateusz Dymczyk Avatar asked May 19 '10 20:05

Mateusz Dymczyk


2 Answers

As Péter points out, you need to pick one style and stick with it, since the style adopted for the @Id annotation will be used for everything.

Beyond that, it's simply a matter of taste. Both options work, so go for the one you prefer. Some people prefer that Hibernate injects via methods, so that they can change the implementation subtly if they need to. I prefer injecting via fields, since I find it cumbersome to have to expose all properties via getter/setter methods (7 lines vs 1 line) when in 99.9% of the times they're going to work as simple variables (and in any case I can switch the annotation style if/when I need to write custom setter functionality anyway).

There are no performance or functionality differences between the two, so choose whichever you prefer (or perhaps more importantly, whichever your team/tools prefer).

like image 109
Andrzej Doyle Avatar answered Sep 21 '22 15:09

Andrzej Doyle


With the @Id annotation, there is a difference: if it is on the getter, Hibernate tries to get/set all class members via their regular getters/setters, while if it is on the member variable, Hibernate will access all the member variables directly.

In other words, you can't mix styles within the same entity.

like image 28
Péter Török Avatar answered Sep 19 '22 15:09

Péter Török