This question is somewhat related to Hibernate Annotation Placement Question.
But I want to know which is better? Access via properties or access vi
I prefer accessors, since I can add some business logic to my accessors whenever I need. Here's an example:
@Entity
public class Person {
@Column("nickName")
public String getNickName(){
if(this.name != null) return generateFunnyNick(this.name);
else return "John Doe";
}
}
Besides, if you throw another libs into the mix (like some JSON-converting lib or BeanMapper or Dozer or other bean mapping/cloning lib based on getter/setter properties) you'll have the guarantee that the lib is in sync with the persistence manager (both use the getter/setter).
Another point in favor of field access is that otherwise you are forced to expose setters for collections as well what, for me, is a bad idea as changing the persistent collection instance to an object not managed by Hibernate will definitely break your data consistency.
So I prefer having collections as protected fields initialized to empty implementations in the default constructor and expose only their getters. Then, only managed operations like clear(), remove(), removeAll() etc are possible that will never make Hibernate unaware of changes.
I prefer fields, but I've run into one situation that seems to force me to place the annotations on getters.
With the Hibernate JPA implementation, @Embedded doesn't seem to work on fields. So that has to go on the getter. And once you put that on the getter, then the various @Column annotations have to go on the getters too. (I think Hibernate doesn't want mixing fields and getters here.) And once you're putting @Column on getters in one class, it probably makes sense to do that throughout.
i thinking about this and i choose method accesor
why?
because field and methos accesor is the same but if later i need some logic in load field, i save move all annotation placed in fields
regards
Grubhart
To make your classes cleaner, put the annotation in the field then use @Access(AccessType.PROPERTY)
That really depends on a specific case -- both options are available for a reason. IMO it boils down to three cases: