Hibernate access strategy for @Id property

Viewed 451

The Hibernate access strategy is specified implicitly by annotating the primary key attribute or its getter method with an @Id annotation. So depending on the @Id access strategy, it is applied to all the properties (or fields).

Is it possible to set FIELD access on the entity object but property access on the @Id property only? How should it be configured?

1 Answers

According to the hibernate documentation:

The default access strategy mechanism can be overridden with the JPA @Access annotation.

And according to the JPA specification:

2.3.2 Explicit Access Type

An access type for an individual entity class, mapped superclass, or embeddable class can be specified for that class independent of the default for the entity hierarchy by means of the Access annotation applied to the class. This explicit access type specification does not affect the access type of other entity classes or mapped superclasses in the entity hierarchy. The following rules apply:

  • When Access(FIELD) is applied to an entity class, mapped superclass, or embeddable class, mapping annotations may be placed on the instance variables of that class, and the persistence provider runtime accesses persistent state via the instance variables defined by the class. All non-transient instance variables that are not annotated with the Transient annotation are persistent. When Access(FIELD) is applied to such a class, it is possible to selectively designate individual attributes within the class for property access. To specify a persistent property for access by the persistence provider runtime, that property must be designated Access(PROPERTY). The behavior is undefined if mapping annotations are placed on any properties defined by the class for which Access(PROPERTY) is not specified. Persistent state inherited from superclasses is accessed in accordance with the access types of those superclasses.

...

So, you can do something like this:

@Entity(name = "Book")
@Access(AccessType.FIELD)
public static class Book {

    // ...

    @Id
    @Access(AccessType.PROPERTY)
    public Long getId() {
        return id;
    }

    // ...
}
Related