Field Access vs Property Access in JPA and Hibernate

/, JPA/Field Access vs Property Access in JPA and Hibernate
Note:
Maven dependencies used all over JPA tutorials same. Please follow "Setting up Project" section to understand about project configuration.
persistence.xml and other code files reused from How to Persist an Entity in data base using JPA?
Each Sample application from download includes SQL file also.
  • The JPA Specification allows access the properties of a class either directly through fields or indirectly through getter and setter methods.
  • JPA introduced standard annotation to control this behaviour in JPA 2.0 (JSR-317).
  • The default behaviour is, location of the mandatory id property of the POJO with @Id  annotation in hibernate determines the access level of this domain object.
  • For example @Id annotation located at the field level then that entity access behaviour is Field Access  (OR) if @Id annotation located at the getter method entity access behaviour is Property Access. This is default behaviour.

Default behavior – Field Access :

Default behavior – Property Access :

Overriding the default behaviour :

  • JPA provides @Access annotation for overriding the default behavior, by using AccessType.FIELD and AccessType.PROPERTY. If you set @Access on the class/entity level, Hibernate accesses all properties of the class according to the selected strategy. You then set any other mapping annotations, including the @Id, on either fields or getter methods, respectively.
  • You can also use the @Access annotation to override the access strategy of individ- ual properties.
  • JPA supports Mixed Access also, it means you can locate annotations some at field level and some at property level.

Leave A Comment