Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate/JPA - annotating bean methods vs fields [duplicate]

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; }  } 
like image 344
benstpierre Avatar asked Jun 02 '09 21:06

benstpierre


2 Answers

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

The Hibernate Annotations reference guide has proven to be an extremely useful resource for questions like this and details how access types cascade down hierarchies.

like image 134
Steve Skrla Avatar answered Sep 23 '22 13:09

Steve Skrla


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

Hibernate Annotations - Which is better, field or property access?

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

like image 24
duffymo Avatar answered Sep 26 '22 13:09

duffymo