views:

968

answers:

4

I have a simple question about usage of Hibernate. I keep seeing people using JPA annotations in one of two ways by annotating the fields of a class and also by annotating the get method on the corresponding beans.

My question is as follows: Is there a difference between annotating fields and bean methods with JPA annoations such as @Id.

example:

@Entity
public class User
{

**@ID**
private int id;

public int getId(){
return this.id;
}

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

}

-----------OR-----------

@Entity
public class User
{


private int id;

**@ID**
public int getId(){
return this.id;
}

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

}
+7  A: 

Yes, if you annotate the fields, Hibernate will use field access to set and get those fields. If you annotate the methods, hibernate will use getters and setters. Hibernate will pick the access method based on the location of the @Id annotation and to my knowledge you cannot mix and match. If you annotate a field with @Id, annotations on methods will be ignored and visa versa. You can also manually set the method with the class level annotation @AccessType

http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/ has proven to be an extremely useful resource for questions like this and details how access types cascade down hierarchies.

Ambience
@David - Yes, I believe it is the same for JPA. However JPA does not support @AccessType
Ambience
+2  A: 

Yes, I believe you want to search on field versus property access:

http://stackoverflow.com/questions/594597/hibernate-annotations-which-is-better-field-or-property-access

The Spring preference is field access. That's what I follow.

duffymo
A: 

Is the answer aplyed to hibernate the same for the other JPA implementations ?

David Hofmann
A: 

My recommendation is to annotate the methods. By doing so, you gain a little flexibility. For example, let's say you have a few classes: AbstractEntity, StringIdEntity, and AutoIdEntity. AbstractEntity defines the id field/getter/setter. The classes StringIdEntity/AutoIdEntity inherit from AbstractEntity, but use different @Id strategies. If you annotate the field, you cannot change it from class to another. If you annotate the methods, you mark getId() as @Transient/abstract in AbstractEntity and then in the subclasses, you simply override the method and apply the strategy you wish to use. I used to annotate fields myself and ran into this and decided that I will always annotate methods moving forward. So, even if you don't see the benefits of annotating methods immediately, it may become obvious down the line when you have so many classes that switching is going to become an absolute headache.

Brian