JPA Field Access, Property Access, and Mixed Access Strategies

Field Access Strategy

When using field access in JPA, annotations are placed directly on the entity fields. The persistence provider accesses these fields directly through reflection, bypassing any getter and setter methods that may exist. The field access strategy offers two annotation styles:

Style One

@Id private Long employeeId;

Style Two

@Id
private Long employeeId;

Property Access Strategy

With property access, annotations are placed on getter methods. The persistence provider calls these methods to access and modify entity state. Property access also supports two annotation formats:

Style One

@Id public Long getEmployeeId() {
    return employeeId;
}

Style Two

@Id
public Long getEmployeeId() {
    return employeeId;
}

Mixed Access Strategy

Mixed access allows combining both field and property access within a single entity. This approach is useful when you need to perform data transformation during database read/write operations while maintaining diffeernt internal representations.

Consider a scenario where phone numbers need area code prefixing when stored in the database but should be displayed without prefixes. The following implementation demonstrates mixed access:

import javax.persistence.*;

@Entity
@Access(AccessType.FIELD)
public class StaffMember {
    @Id
    private Long staffId;
    
    private String fullName;
    
    @Transient
    private String contactNumber;
    
    private Double monthlySalary;
    
    public Long getStaffId() {
        return staffId;
    }
    
    public void setStaffId(Long staffId) {
        this.staffId = staffId;
    }
    
    public String getFullName() {
        return fullName;
    }
    
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
    
    public String getContactNumber() {
        return "+86-" + contactNumber;
    }
    
    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }
    
    @Access(AccessType.PROPERTY)
    @Column(name = "contact_number")
    public String getDatabaseContactNumber() {
        return "+86-" + this.contactNumber;
    }
    
    public void setDatabaseContactNumber(String contactNumber) {
        this.contactNumber = contactNumber.substring(4);
    }
    
    public Double getMonthlySalary() {
        return monthlySalary;
    }
    
    public void setMonthlySalary(Double monthlySalary) {
        this.monthlySalary = monthlySalary;
    }
}

The implementation uses @Access(AccessType.FIELD) to establish field access as the default strategy. The @Transient annotation prevents dual persistence of the contact number field. The @Access(AccessType.PROPERTY) annotation on the getDatabaseContactNumber() method enables custom data transformation for database operations.

Tags: jpa Entity Mapping Access Strategies Field Access Property Access

Posted on Thu, 14 May 2026 13:54:48 +0000 by BeanoEFC