当未定义 getter/setter 方法时,JPA 提供程序如何访问(私有)字段值?

How does a JPA provider access (private) field values when no getter/setter method are defined?

@Entity访问模式为“字段”访问时,实体class字段可以标记为private,只是想了解一下在这种情况下,提供者如何能够访问实体状态,因为字段被标记为私有并且在 class 之外不可见?

编辑 #1 - 如您所知,对于字段访问,getter 和 setter 方法是可选的。所以我想了解当没有提供 getter/setter 方法时,提供者将如何访问该字段。希望这能澄清我的问题。

提供商可以使用反射来访问 class 实例上的私有字段。

参考官方JPA specification(最终版,JPA 2.1)2.2节(第24页)我们发现:

The persistent state of an entity is accessed by the persistence provider runtime either via JavaBeans style property accessors (“property access”) or via instance variables (“field access”). Whether persistent properties or persistent fields or a combination of the two is used for the provider’s access to a given class or entity hierarchy is determined as described in Section 2.3, “Access Type”.

在第 2.3.1 节(第 27 页)中,此定义更加具体 - 关于您的问题:

By default, a single access type (field or property access) applies to an entity hierarchy. The default access type of an entity hierarchy is determined by the placement of mapping annotations on the attributes of the entity classes and mapped superclasses of the entity hierarchy that do not explicitly specify an access type. [...]

• When field-based access is used, the object/relational mapping annotations for the entity class annotate the instance variables, and the persistence provider runtime accesses instance variables directly. All non-transient instance variables that are not annotated with the Transient annotation are persistent.

• When property-based access is used, the object/relational mapping annotations for the entity class annotate the getter property accessors, and the persistence provider runtime accesses persistent state via the property accessor methods. All properties not annotated with the Transient annotation are persistent.

术语直接指的是一种访问策略,它允许操作对象的字段(值)而无需使用getter/setter 方法。在 Java 和大多数 OR 映射器(至少我知道的)中,这是通过 Introspection - using the Java Reflection API 实现的。这样,可以检查 类' 字段并将其操作为来自(关系)数据库条目(即它们各自的列)的 hold/represent 数据值。

例如,提供者 Hibernate 在其 User Guide 中给出了以下解释:

2.5.9. Access strategies

As a JPA provider, Hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties). By default, the placement of the @Id annotation gives the default access strategy.

重要说明

尝试不同的访问策略时要小心!必须满足以下要求(JPA 规范,第 28 页):

All such classes in the entity hierarchy whose access type is defaulted in this way must be consistent in their placement of annotations on either fields or properties, such that a single, consistent default access type applies within the hierarchy.

希望对您有所帮助。