Field access maps persistent state by allowing Hibernate or another JPA provider to read and write member fields directly instead of invoking getter and setter methods. It preserves freedom to design accessors, including making them non-public or omitting them. section 3.2.3
Apply field access according to these mapping rules:
- Place @Id on a field to select field access for the entity; fields then represent persistent properties by default. section 5.2.2
- Keep mapping annotations on fields when the entity uses field access; setter methods are not the annotation target for this strategy. section 6.1.2
- Use @Access(AccessType.PROPERTY) or @Access(AccessType.FIELD) to override the default for a class or individual property. section 6.1.2
- Expect embedded classes and mapped-superclass properties to inherit the owning entity's default or explicitly selected access strategy. section 6.1.2
An identifier with field access
An entity can keep its identifier private while exposing only a getter: @Id and @GeneratedValue annotate the private id field, so Hibernate accesses that field directly. A public setter is unnecessary because primary-key values should not change. section 5.2.2
Listing 6.1 Overriding access strategy for the name property
Path: Ch06/mapping-value-types/src/main/java/com/manning/javapersistence /ch06/model/Item.java @Entity public class Item { @Id #1 @GeneratedValue(generator = "ID_GENERATOR") #1 private Long id; #1 @Access(AccessType.PROPERTY) #2 @Column(name = "ITEM_NAME") #2 private String name; #2 public String getName() { #3 return name; #3 } #3 public void setName(String name) { #3 this.name = #3 !name.startsWith("AUCTION: ") ? "AUCTION: " + name : name; #3 } #3 } #1 The <kbd>Item</kbd> entity defaults to field access. The <kbd>@Id</kbd> is on the field. #2 The <kbd>@Access(AccessType.PROPERTY)</kbd> setting on the <kbd>name</kbd> field switches this particular property to be accessed at runtime by the JPA provider through getter/setter. #3 Hibernate or Spring Data JPA using Hibernate calls <kbd>getName()</kbd> and <kbd>setName()</kbd> when loading and storing items.
Inspect a mixed mapping where the entity defaults to field access but the name property explicitly uses property access. section 6.1.2
