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; } }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With