5
  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?

8

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

  • Okay, but my question is: any one of them are better for any reason? Safer? I will improve my question a bit. – CsBalazsHungary Oct 9 '14 at 8:36
  • I added some information. – ftr Oct 9 '14 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.