跳到主要内容

对象映射基础

Doubao 中英对照 Object Mapping Fundamentals

本节介绍 Spring Data 对象映射、对象创建、字段与属性访问、可变性与不可变性的基础知识。请注意,本节仅适用于不使用底层数据存储对象映射的 Spring Data 模块(如 JPA)。另请务必查阅特定存储部分,了解特定存储的对象映射内容,例如索引、自定义列名或字段名等。

Spring Data 对象映射的核心职责是创建领域对象的实例,并将存储原生的数据结构映射到这些实例上。这意味着我们需要两个基本步骤:

  1. 使用所暴露的构造函数之一进行实例创建。

  2. 实例填充,即将所有暴露的属性物化。

对象创建​

Spring Data 会自动尝试检测持久化实体的构造函数,用于物化该类型的对象。解析算法如下:

  1. 如果存在一个用 @PersistenceCreator 注解的静态工厂方法,则使用它。

  2. 如果只有一个构造函数,则使用它。

  3. 如果有多个构造函数,且恰好有一个用 @PersistenceCreator 注解,则使用它。

  4. 如果类型是 Java Record,则使用其规范构造函数。

  5. 如果存在无参构造函数,则使用它。其他构造函数将被忽略。

值解析假定构造函数/工厂方法的参数名与实体的属性名相匹配,即解析将按照要填充该属性的方式进行,包括映射中的所有定制(不同数据存储的列名或字段名等)。这还要求 class 文件中包含参数名信息,或构造函数上存在 @ConstructorProperties 注解。

可以使用 Spring Framework 的 @Value 值注解并配合特定存储的 SpEL 表达式来自定义值解析。更多详细信息请参阅特定存储映射的相关章节。

Object creation internals

To avoid the overhead of reflection, Spring Data object creation uses a factory class generated at runtime by default, which will call the domain classes constructor directly. I.e. for this example type:

class Person {
Person(String firstname, String lastname) { … }
}
java

we will create a factory class semantically equivalent to this one at runtime:

class PersonObjectInstantiator implements ObjectInstantiator {

Object newInstance(Object... args) {
return new Person((String) args[0], (String) args[1]);
}
}
java

This gives us a roundabout 10% performance boost over reflection. For the domain class to be eligible for such optimization, it needs to adhere to a set of constraints:

  • it must not be a private class

  • it must not be a non-static inner class

  • it must not be a CGLib proxy class

  • the constructor to be used by Spring Data must not be private

If any of these criteria match, Spring Data will fall back to entity instantiation via reflection.

属性填充​

一旦创建了实体的实例,Spring Data 会填充该类所有剩余的持久化属性。除非已由实体的构造函数填充(即已通过其构造函数参数列表消费),否则标识符属性会最先被填充,以便解析循环对象引用。此后,构造函数尚未填充的所有非瞬态属性都会被设置到实体实例上。为此,我们使用以下算法:

  1. 如果属性是不可变的,但暴露了 with… 方法(见下文),我们使用 with… 方法创建带有新属性值的新实体实例。

  2. 如果定义了属性访问(即通过 getter 和 setter 访问),我们调用 setter 方法。

  3. 如果属性是可变的,我们直接设置字段。

  4. 如果属性是不可变的,我们使用持久化操作所用的构造函数(见对象创建)创建实例的副本。

  5. 默认情况下,我们直接设置字段值。

Property population internals

Similarly to our optimizations in object construction we also use Spring Data runtime generated accessor classes to interact with the entity instance.

class Person {

private final Long id;
private String firstname;
private @AccessType(Type.PROPERTY) String lastname;

Person() {
this.id = null;
}

Person(Long id, String firstname, String lastname) {
// Field assignments
}

Person withId(Long id) {
return new Person(id, this.firstname, this.lastname);
}

void setLastname(String lastname) {
this.lastname = lastname;
}
}
java
class PersonPropertyAccessor implements PersistentPropertyAccessor {

private static final MethodHandle firstname; 2

private Person person; 1

public void setProperty(PersistentProperty property, Object value) {

String name = property.getName();

if ("firstname".equals(name)) {
firstname.invoke(person, (String) value); 2
} else if ("id".equals(name)) {
this.person = person.withId((Long) value); 3
} else if ("lastname".equals(name)) {
this.person.setLastname((String) value); 4
}
}
}
java
  • PropertyAccessor’s hold a mutable instance of the underlying object. This is, to enable mutations of otherwise immutable properties.

  • By default, Spring Data uses field-access to read and write property values. As per visibility rules of private fields, MethodHandles are used to interact with fields.

  • The class exposes a withId(…) method that’s used to set the identifier, e.g. when an instance is inserted into the datastore and an identifier has been generated. Calling withId(…) creates a new Person object. All subsequent mutations will take place in the new instance leaving the previous untouched.

  • Using property-access allows direct method invocations without using MethodHandles.

This gives us a roundabout 25% performance boost over reflection. For the domain class to be eligible for such optimization, it needs to adhere to a set of constraints:

  • Types must not reside in the default or under the java package.

  • Types and their constructors must be public

  • Types that are inner classes must be static.

  • The used Java Runtime must allow for declaring classes in the originating ClassLoader. Java 9 and newer impose certain limitations.

By default, Spring Data attempts to use generated property accessors and falls back to reflection-based ones if a limitation is detected.

请看以下实体:

class Person {

private final @Id Long id; 1
private final String firstname, lastname; 2
private final LocalDate birthday;
private final int age; 3

private String comment; 4
private @AccessType(Type.PROPERTY) String remarks; 5
private @Transient String summary; 6

static Person of(String firstname, String lastname, LocalDate birthday) { 7

return new Person(null, firstname, lastname, birthday,
Period.between(birthday, LocalDate.now()).getYears());
}

Person(Long id, String firstname, String lastname, LocalDate birthday, int age) { 7

this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.birthday = birthday;
this.age = age;
}

Person withId(Long id) { 1
return new Person(id, this.firstname, this.lastname, this.birthday, this.age);
}

void setRemarks(String remarks) { 5
this.remarks = remarks;
}
}
java
  • 标识符属性是 final 的,但在构造函数中被设置为 null。该类暴露了一个 withId(…) 方法,用于设置标识符,例如当实例插入数据存储后生成了标识符时。创建新实例时,原有的 Person 实例保持不变。对于其他由存储管理、但可能在持久化操作中需要更改的属性,通常也采用相同模式。wither 方法是可选的,因为持久化构造函数(见第 6 项)实际上就是一个复制构造函数,设置该属性会被转换为创建一个应用了新标识符值的新实例。

  • firstname 和 lastname 属性是普通的不可变属性,可能通过 getter 暴露。

  • age 属性是不可变属性,但派生自 birthday 属性。在所示设计中,数据库值会覆盖默认值,因为 Spring Data 使用唯一声明的构造函数。即使本意是优先使用计算值,该构造函数也必须将 age 作为参数(以便可能忽略它),否则属性填充步骤会尝试设置 age 字段,而由于它是不可变的且没有 with… 方法,将导致失败。

  • comment 属性是可变的,通过直接设置其字段来填充。

  • remarks 属性是可变的,通过调用 setter 方法来填充。

  • summary 属性是瞬态的,不会被持久化,因为它用 @Transient 注解。Spring Data 不使用 Java 的 transient 关键字来排除属性的持久化,因为 transient 属于 Java 序列化框架。请注意,该属性可以用于持久化构造函数,但其值默认为 null(如果属性类型是基本类型,则为相应的基本类型初始值)。

  • 该类暴露了一个工厂方法和一个构造函数用于对象创建。这里的核心思想是使用工厂方法而非额外的构造函数,以避免通过 @PersistenceCreator 进行构造函数消歧。取而代之的是,属性的默认值在工厂方法内处理。如果您希望 Spring Data 使用工厂方法进行实例化,请用 @PersistenceCreator 注解它。

通用建议​

  • 尽量坚持使用不可变对象 —— 不可变对象创建起来很直接,因为物化对象只需调用其构造函数。此外,这还避免了在领域对象中充斥 setter 方法而让客户端代码能够操纵对象状态。如果确实需要 setter,最好将其设为包级私有,使其只能被有限的同包类型调用。仅通过构造函数物化比属性填充快最多可达 30%。

  • 提供全参构造函数 —— 即使您不能或不想将实体建模为不可变值,提供一个接受实体所有属性(包括可变属性)作为参数的构造函数仍然是有价值的,因为这让对象映射可以跳过属性填充以获得最佳性能。

  • 使用工厂方法而非重载构造函数来避免使用 @PersistenceCreator —— 在需要全参构造函数以获得最佳性能的同时,我们通常还想暴露更多面向特定应用场景、省略自动生成标识符等内容的构造函数。一种成熟的做法是使用静态工厂方法来暴露这些全参构造函数的变体。

  • 确保遵守允许使用生成的实例化器和属性访问器类的约束 ——

  • 对于需要生成的标识符,仍然使用 final 字段配合全参持久化构造函数(首选)或 with… 方法 ——

  • 使用 Lombok 避免样板代码 —— 由于持久化操作通常需要一个接受所有参数的构造函数,其声明会变成枯燥重复的参数到字段的样板赋值,使用 Lombok 的 @AllArgsConstructor 可以最好地避免这些。

覆盖属性​

Java 允许灵活设计领域类,子类可以定义一个在其父类中已以相同名称声明的属性。请看以下示例:

public class SuperType {

private CharSequence field;

public SuperType(CharSequence field) {
this.field = field;
}

public CharSequence getField() {
return this.field;
}

public void setField(CharSequence field) {
this.field = field;
}
}

public class SubType extends SuperType {

private String field;

public SubType(String field) {
super(field);
this.field = field;
}

@Override
public String getField() {
return this.field;
}

public void setField(String field) {
this.field = field;

// optional
super.setField(field);
}
}
java

两个类都使用可赋值的类型定义了 field。然而,SubType 遮蔽了 SuperType.field。根据类的设计,使用构造函数可能是设置 SuperType.field 的唯一默认方式。另一种方式是在 setter 中调用 super.setField(…) 来设置 SuperType 中的 field。所有这些机制都会在某种程度上产生冲突,因为这些属性共享同一名称,却可能代表两个不同的值。如果类型不可赋值,Spring Data 会跳过超类型属性。也就是说,被覆盖属性的类型必须可赋值给其超类型属性的类型,才会被注册为覆盖,否则该超类型属性被视为瞬态。我们通常建议使用不同的属性名。

Spring Data 模块通常支持持有不同值的被覆盖属性。从编程模型的角度来看,有几点需要考虑:

  1. 哪个属性应该被持久化(默认为所有声明的属性)?您可以通过用 @Transient 注解属性来排除它们。

  2. 如何在您的数据存储中表示这些属性?对不同的值使用相同的字段/列名通常会导致数据损坏,因此您应该用显式的字段/列名注解至少其中一个属性。

  3. 不能使用 @AccessType(PROPERTY),因为在不对 setter 实现做进一步假设的情况下,通常无法设置超属性。

Kotlin 支持​

Spring Data 会适配 Kotlin 的特性,以支持对象创建和变更。

Kotlin 对象创建​

Kotlin 类支持实例化,所有类默认都是不可变的,需要显式声明属性来定义可变属性。

Spring Data 会自动尝试检测持久化实体的构造函数,用于物化该类型的对象。解析算法如下:

  1. 如果存在用 @PersistenceCreator 注解的构造函数,则使用它。

  2. 如果类型是 Kotlin 数据类,则使用其主构造函数。

  3. 如果存在一个用 @PersistenceCreator 注解的静态工厂方法,则使用它。

  4. 如果只有一个构造函数,则使用它。

  5. 如果有多个构造函数,且恰好有一个用 @PersistenceCreator 注解,则使用它。

  6. 如果类型是 Java Record,则使用其规范构造函数。

  7. 如果存在无参构造函数,则使用它。其他构造函数将被忽略。

请看以下 data 类 Person:

data class Person(val id: String, val name: String)
kotlin

上面的类编译后是一个带有显式构造函数的典型类。我们可以通过添加另一个构造函数并用 @PersistenceCreator 注解它来定制该类,以表明构造函数偏好:

data class Person(var id: String, val name: String) {

@PersistenceCreator
constructor(id: String) : this(id, "unknown")
}
kotlin

Kotlin 通过允许在未提供参数时使用默认值来支持参数可选性。当 Spring Data 检测到带有参数默认值的构造函数时,如果数据存储未提供值(或仅返回 null),它会让这些参数保持缺失,以便 Kotlin 应用参数默认值。请看以下为 name 应用参数默认值的类:

data class Person(var id: String, val name: String = "unknown")
kotlin

每当 name 参数不在结果中或其值为 null 时,name 默认为 unknown。

备注

Spring Data 不支持委托属性。映射元数据会过滤 Kotlin 数据类的委托属性。在所有其他情况下,您可以通过用 @Transient 注解该属性来排除委托属性的合成字段。

Kotlin 数据类的属性填充​

在 Kotlin 中,所有类默认都是不可变的,需要显式声明属性来定义可变属性。请看以下 data 类 Person:

data class Person(val id: String, val name: String)
kotlin

这个类实际上是不可变的。它允许创建新实例,因为 Kotlin 会生成一个 copy(…) 方法,该方法通过复制现有对象的所有属性值、并应用作为参数提供的属性值来创建新的对象实例。

Kotlin 覆盖属性​

Kotlin 允许声明属性覆盖,以在子类中更改属性。

open class SuperType(open var field: Int)

class SubType(override var field: Int = 1) :
SuperType(field) {
}
kotlin

这样的安排会产生两个名为 field 的属性。Kotlin 为每个类中的每个属性生成属性访问器(getter 和 setter)。实际上,代码如下所示:

public class SuperType {

private int field;

public SuperType(int field) {
this.field = field;
}

public int getField() {
return this.field;
}

public void setField(int field) {
this.field = field;
}
}

public final class SubType extends SuperType {

private int field;

public SubType(int field) {
super(field);
this.field = field;
}

public int getField() {
return this.field;
}

public void setField(int field) {
this.field = field;
}
}
java

SubType 上的 getter 和 setter 只设置 SubType.field,而不设置 SuperType.field。在这种安排下,使用构造函数是设置 SuperType.field 的唯一默认方式。在 SubType 中添加一个通过 this.SuperType.field = … 设置 SuperType.field 的方法是可行的,但这超出了受支持的约定范围。属性覆盖会在某种程度上产生冲突,因为这些属性共享同一名称,却可能代表两个不同的值。我们通常建议使用不同的属性名。

Spring Data 模块通常支持持有不同值的被覆盖属性。从编程模型的角度来看,有几点需要考虑:

  1. 哪个属性应该被持久化(默认为所有声明的属性)?您可以通过用 @Transient 注解属性来排除它们。

  2. 如何在您的数据存储中表示这些属性?对不同的值使用相同的字段/列名通常会导致数据损坏,因此您应该用显式的字段/列名注解至少其中一个属性。

  3. 不能使用 @AccessType(PROPERTY),因为无法设置超属性。

Kotlin 值类​

Kotlin 值类旨在构建更具表达力的领域模型,使底层概念更加明确。Spring Data 可以读写使用值类定义属性的类型。

请看以下领域模型:

@JvmInline
value class EmailAddress(val theAddress: String) 1

data class Contact(val id: String, val name:String, val emailAddress: EmailAddress) 2
kotlin
  • 一个简单的值类,具有不可空的值类型。

  • 使用 EmailAddress 值类定义属性的数据类。

备注

使用非基本类型值类的不可空属性,在编译后的类中会被扁平化到值类型。可空的基本类型值类或可空的值中值类型,会以其包装类型表示,这会影响值类在数据库中的表示方式。