Java JPA – Where to Put JPA Annotations: Field or Getter?

annotationsjavajpa

  1. version in field:

    @Column(name = "SAMPLE_STRING")  
    private String sampleString;
    
    public String getSampleString(){  
      return sampleString;  
    }
    
  2. version in getter:

    private String sampleString;
    
    @Column(name = "SAMPLE_STRING")  
    public String getSampleString(){  
      return sampleString;  
    }  
    

It seems both are working well, are there reasons not to use one of them, or just a good practice why I should prefer one of them? Is any one of them safer/better/desirable?

Best Answer

Taken from https://stackoverflow.com/questions/14028198/jpa-why-the-annotations-are-applied-on-getter-or-field, if you apply the annotation to the field, the jpa provider directly sets the field. If you annotate the getter, the JPA provider uses the accessor methods.

See Chapter 2.3.1 of the specification here.

I prefer field access for a couple of reasons:
- you do not need to provide getters and setters for all properties, so this actually enhances encapsulation.
- i prefer to have the information grouped at the beginning of a class on the fields because I thinks it is more readable