2.5.2.1. Explicit Access
The access type of a class or individual persistent attributes can be specified explicitly using the @Access annotation or access attribute on the XML elements used to define persistent attributes.
When explicitly defining access, specify the explicit access type for the class and then apply the @Access annotation or access XML attribute to individual fields or properties.
If explicit FIELD or PROPERTY is specified at the class level, all eligible non-transient fields or properties will be persistent.
If using class level FIELD access, non-persistent fields must be transient or annotated with @Transient.
If using class level PROPERTY access, non-persistent properties must be annotated @Transient or excluded using the transient XML attribute.
Refer to the JPA specification for specific rules regarding the use of explicit access with embeddables and within an inheritance hierarchy.
This entity definitions shows how multiple access types may be specified on an entity:
@Entity
@Access(AccessType.FIELD)
public class PaymentContract {
@Id
private String id;
@Temporal(TemporalType.DATE)
private String contractDate;
@Transient
private String terms;
@Version
private int version;
@Lob
@Access(AccessType.PROPERTY)
public String getContractTerms() {
return terms;
}
public void setContractTerms(String terms) {
// Format string before persisting
this.terms = formatTerms(terms);
}
...
}
The equivalent declarations in XML:
<entity-mappings xmlns="https://jakarta.ee/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence/orm https://jakarta.ee/xml/ns/persistence/orm/orm_3_0.xsd"
version="3.0">
<entity class="org.xyz.PaymentContract" access="FIELD">
<attributes>
<id name="id"/>
<basic name="contractTerms" access="PROPERTY">
<lob/>
</basic>
<basic name="contractDate">
<temporal>DATE</temporal>
</basic>
<version name="version"/>
<transient name="terms"/>
</attributes>
</entity>
</entity-mappings>
|
|
When using property access, only the getter and setter method for a property should ever access the underlying persistent field directly. Other methods, including internal business methods in the persistent class, should go through the getter and setter methods when manipulating persistent state. Also, take care when adding business logic to your getter and setter methods. Consider that they are invoked by the persistence implementation to load and retrieve all persistent state; other side effects might not be desirable. |
The remainder of this document uses the term "persistent field" to refer to either a persistent field or a persistent property.