From b5d5506311cb54313fcaa827e9ce7802c3b0932d Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Wed, 29 Aug 2018 11:56:20 +0200 Subject: [PATCH] DATACMNS-1374 - Rewrite of reference documentation section on object mapping. --- src/main/asciidoc/index.adoc | 2 + ...ng-mutability.adoc => object-mapping.adoc} | 227 +++++++++++++++++- 2 files changed, 218 insertions(+), 11 deletions(-) rename src/main/asciidoc/{mapping-mutability.adoc => object-mapping.adoc} (50%) diff --git a/src/main/asciidoc/index.adoc b/src/main/asciidoc/index.adoc index 4927012fe..2d3e6eff6 100644 --- a/src/main/asciidoc/index.adoc +++ b/src/main/asciidoc/index.adoc @@ -24,6 +24,8 @@ include::preface.adoc[] :leveloffset: +1 include::dependencies.adoc[] +include::object-mapping.adoc[] + include::repositories.adoc[] include::repository-projections.adoc[] diff --git a/src/main/asciidoc/mapping-mutability.adoc b/src/main/asciidoc/object-mapping.adoc similarity index 50% rename from src/main/asciidoc/mapping-mutability.adoc rename to src/main/asciidoc/object-mapping.adoc index 1646851f0..02f59c10b 100644 --- a/src/main/asciidoc/mapping-mutability.adoc +++ b/src/main/asciidoc/object-mapping.adoc @@ -1,7 +1,212 @@ [[mapping.mutability]] -= Object Mutation, Creation, and Property Access += Object Mapping Fundamentals -This section covers object mutability, object creation, and property access. +This section covers the fundamentals of Spring Data object mapping, object creation, field and property access, mutability and immutability. +Note, that this section only applies to Spring Data modules that do not use the object mapping of the underlying data store (like JPA). +Also be sure to consult the store specific sections for store specific object mapping, like indexes, customizing columnd or field names or the like. + +Core responsibility of the Spring Data object mapping is to create instances of domain objects and map the store-native data structures onto those. +This means we need two fundamental steps: + +1. Instance creation by using one of the constructors exposed +2. Instance population to materialize all exposed properties. + +[[mapping.object-creation]] +== Object creation + +Spring Data automatically tries to detect a persistent entity's constructor to be used to materialize objects of that type. +The resolution algorithm works as follows: + +1. If there's a no-argument constructor, it will be used. +Other constructors will be ignored. +2. If there's a single constructor taking arguments, it will be used. +3. If there are multiple constructors taking arguments, the one to be used by Spring Data will have to be annotated with `@PersistenceConstructor`. + +The value resolution assumes constructor argument names to match the property names of the entity, i.e. the resolution will be performed as if the property was to be populated, including all customizations in mapping (different datastore column or field name etc.). +This also requires either parameter names information available in the class file or an `@ConstructorProperties` annotation being present on the constructor. + +The value resolution can be customized by using Spring Framework's `@Value` value annotation using a store-specific SpEL expression. +Please consult the section on store specific mappings for further details. + +[[mapping.object-creation.details]] +.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: + +[source, java] +---- +class Person { + Person(String firstname, String lastname) { … } +} +---- + +we will create a factory class semantically equivalent to this one at runtime: + +[source, java] +---- +class PersonObjectInstantiator implements ObjectInstantiator { + + Object newInstance(Object... args) { + return new Person((String) args[0], (String) args[1]); + } +} +---- + +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 criterias match, Spring Data will fall back to entity instantiation via reflection. +**** + +[[mapping.property-population]] +== Property population + +Once an instance of the entity has been created, Spring Data populates all remaining persistent properties of that class. +Unless already populated by the entity's constructor (i.e. consumed through its constructor argument list), the identifier property will be populated first to allow the resolution of cyclic object references. +After that, all non-transient properties that have not already been populated by the constructor are set on the entity instance. +For that we use the following algorithm: + +1. If the property is immutable but exposes a wither method (see below), we use the wither to create a new entity instance with the new property value. +2. If property access (i.e. access through getters and setters) is defined, we're invoking the setter method. +3. By default, we set the field value directly. + +[[mapping.property-population.details]] +.Property population internals +**** +Similarly to our <> we also use Spring Data runtime generated accessor classes to interact with the entity instance. + +[source, java] +---- +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.lastame); + } + + void setLastname(String lastname) { + this.lastname = lastname; + } +} +---- + +[source, 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.…; <2> + } else if ("id".equals(name)) { + this.person = person.withId((Long) value); <3> + } else if ("lastname".equals(name)) { + this.person.setLastname((String) value); <4> + } + } +} +---- + +**** + +Let's have a look a + +.A sample entity +==== +[source, java] +---- +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> + + static Person of(String firstname, String lastname, LocalDate birthday) { <6> + + return new Person(null, firstname, lastname, birthday, + Period.between(birthday, LocalDate.now()).getYears()); + } + + Person(Long id, String firstname, String lastname, LocalDate birthday, int age) { <6> + + 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); + } + + void setRemarks(String remarks) { <5> + this.remarks = remarks; + } +} +---- +==== +<1> The identifier property is final but set to `null` in the constructor. +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. +The original `Person` instance stays unchanged as a new one is created. +The same pattern is usually applied for other properties that are store managed but might have to be changed for persistence operations. +<2> The `firstname` and `lastname` properties are ordinary immutable properties potentially exposed through getters. +<3> The `age` property is an immutable but derived one from the `birthday` property. +With the design shown, the database value will trump the defaulting as Spring Data uses the only declared constructor. +Even if the intend is that the calculation should be preferred, it's important that this constructor also takes `age` as parameter (to potentially ignore it) as otherwise the property population step will attempt to set the age field and fail due to it being immutable and no wither being present. +<4> The `comment` property is mutable is populated by setting its field directly. +<5> The `remarks` properties are mutable and populated by setting the `comment` field directly or by invoking the setter method for +<6> The class exposes a factory method and a constructor for object creation. +The core idea here is to use factory methods instead of additional constructors to avoid the need for constructor disambiguation through `@PersistenceConstructor`. +Instead, defaulting of properties is handled within the factory method. + +== General recommendations + +* _Try to stick to immutable objects_ -- Immutable objects are straight forward to create as materializing an object is then a matter of calling its constructor only. +Also, this avoids your domain objects to be littered with setter methods that allow client code to manipulate the objects state. +If you need those, prefer to make them package protected so that they can only be invoked by a limited amount of colocated types. +Constructor-only materialization is up to 30% faster than if we also have to populate properties. +* _Provide an all-args constructor_ -- Even if you cannot or don't want to model your entities as immutable values, there's still value in providing a constructor that takes all properties of the entity as arguments, including the mutable ones, as this allows the object mapping to skip the property population for optimal performance. +* _Use factory methods instead of overloaded constructors to avoid ``@PersistenceConstructor``_ -- With an all-argument constructor needed for optimal performance, we usually want to expose more application use case specific constructors that omit things like auto-generated identifiers etc. +It's an established pattern to rather use static factory methods to expose these variants of the all-args constructor. +* _Make sure you adhere to the constraints that allow the generated instantiator and property accessor classes to be used_ -- +* _For identifiers to be generated, still use a final field in combination with a wither method_ -- +* _Use Lombok to avoid boilerplate code_ -- As persistence operations usually require a constructor taking all arguments, their declaration becomes a tedious repeatition of boilerplate parameter to field assignments that can best be avoided by using Lombok's `@AllArgsConstructor`. + + +== Old stuff + +=== Immutable objects + +Spring Data's support for complex constructors allows store data to be mapped to immutable objects and is the most effective way to populate Object mutability impacts how Spring Data handles objects for specific functionality that requires Spring Data to change properties of a particular object. Such changes can be Id generation, auditing or as simple as reading back an object. @@ -20,18 +225,18 @@ Such objects have non-`final` fields and typically getters and setters. Consider ---- class Person { - private String id; - private String name; + private String id; + private String name; - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getId() { - return this.id; - } + public String getId() { + return this.id; + } - // other getters/setters omitted for brevity. + // Other getters/setters omitted for brevity. } ---- ====