2.4.3. Property
2.4.3.1. Access type
The access type is guessed from the position of
@Id
or @EmbeddedId
in the entity hierarchy. Sub-entities, embedded objects and mapped superclass inherit the access type from the root entity.
In Hibernate, you can override the access type to:
- use a custom access type strategy
- fine tune the access type at the class level or at the property level
An @AccessType annotation has been introduced to support this behavior. You can define the access type on
- an entity
- a superclass
- an embeddable object
- a property
The access type is overriden for the annotated element, if overriden on a class, all the properties of the given class inherit the access type. For root entities, the access type is considered to be the default one for the whole hierarchy (overridable at class or property level).
If the access type is marked as "property", the getters are scanned for annotations, if the access type is marked as "field", the fields are scanned for annotations. Otherwise the elements marked with @Id or @embeddedId are scanned.
You can override an access type for a property, but the element to annotate will not be influenced: for example an entity having access type
field
, can annotate a field with @AccessType("property")
, the access type will then be property for this attribute, the the annotations still have to be carried on the field.
If a superclass or an embeddable object is not annotated, the root entity access type is used (even if an access type has been define on an intermediate superclass or embeddable object). The russian doll principle does not apply.
@Entity
public class Person implements Serializable {
@Id @GeneratedValue //access type field
Integer id;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "iso2", column = @Column(name = "bornIso2")),
@AttributeOverride(name = "name", column = @Column(name = "bornCountryName"))
})
Country bornIn;
}
@Embeddable
@AccessType("property") //override access type for all properties in Country
public class Country implements Serializable {
private String iso2;
private String name;
public String getIso2() {
return iso2;
}
public void setIso2(String iso2) {
this.iso2 = iso2;
}
@Column(name = "countryName")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}