spring-data.md 148.4 KB
Newer Older
Miykael_xxm's avatar
Miykael_xxm 已提交
1
# Preface
M
Mao 已提交
2 3 4

The Spring Data Commons project applies core Spring concepts to the development of solutions using many relational and non-relational data stores.

Miykael_xxm's avatar
Miykael_xxm 已提交
5
## 1. Project Metadata
M
Mao 已提交
6 7 8 9 10 11 12 13 14 15 16

* Version control: [https://github.com/spring-projects/spring-data-commons](https://github.com/spring-projects/spring-data-commons)

* Bugtracker: [https://github.com/spring-projects/spring-data-commons/issues](https://github.com/spring-projects/spring-data-commons/issues)

* Release repository: [https://repo.spring.io/libs-release](https://repo.spring.io/libs-release)

* Milestone repository: [https://repo.spring.io/libs-milestone](https://repo.spring.io/libs-milestone)

* Snapshot repository: [https://repo.spring.io/libs-snapshot](https://repo.spring.io/libs-snapshot)

Miykael_xxm's avatar
Miykael_xxm 已提交
17
## Reference Documentation
M
Mao 已提交
18

Miykael_xxm's avatar
Miykael_xxm 已提交
19
## 2. Dependencies
M
Mao 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

Due to the different inception dates of individual Spring Data modules, most of them carry different major and minor version numbers. The easiest way to find compatible ones is to rely on the Spring Data Release Train BOM that we ship with the compatible versions defined. In a Maven project, you would declare this dependency in the `<dependencyManagement />` section of your POM as follows:

Example 1. Using the Spring Data release train BOM

```
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-bom</artifactId>
      <version>2021.1.2</version>
      <scope>import</scope>
      <type>pom</type>
    </dependency>
  </dependencies>
</dependencyManagement>
```

The current release train version is `2021.1.2`. The train version uses [calver](https://calver.org/) with the pattern `YYYY.MINOR.MICRO`.
The version name follows `${calver}` for GA releases and service releases and the following pattern for all other versions: `${calver}-${modifier}`, where `modifier` can be one of the following:

* `SNAPSHOT`: Current snapshots

* `M1`, `M2`, and so on: Milestones

* `RC1`, `RC2`, and so on: Release candidates

You can find a working example of using the BOMs in our [Spring Data examples repository](https://github.com/spring-projects/spring-data-examples/tree/master/bom). With that in place, you can declare the Spring Data modules you would like to use without a version in the `<dependencies />` block, as follows:

Example 2. Declaring a dependency to a Spring Data module

```
<dependencies>
  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
  </dependency>
<dependencies>
```

Miykael_xxm's avatar
Miykael_xxm 已提交
61
### 2.1. Dependency Management with Spring Boot
M
Mao 已提交
62 63 64 65

Spring Boot selects a recent version of Spring Data modules for you. If you still want to upgrade to a newer version, set
the `spring-data-releasetrain.version` property to the [train version and iteration](#dependencies.train-version) you would like to use.

Miykael_xxm's avatar
Miykael_xxm 已提交
66
### 2.2. Spring Framework
M
Mao 已提交
67 68 69

The current version of Spring Data modules require Spring Framework 5.3.16 or better. The modules might also work with an older bugfix version of that minor version. However, using the most recent version within that generation is highly recommended.

Miykael_xxm's avatar
Miykael_xxm 已提交
70
## 3. Object Mapping Fundamentals
M
Mao 已提交
71 72 73 74 75 76 77 78 79 80 81 82

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 column 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.

Miykael_xxm's avatar
Miykael_xxm 已提交
83
### 3.1. Object creation
M
Mao 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

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 is a single constructor, it is used.

2. If there are multiple constructors and exactly one is annotated with `@PersistenceConstructor`, it is used.

3. If there’s a no-argument constructor, it is used.
   Other constructors will be ignored.

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.

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) { … }
}
```

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]);
  }
}
```

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.

Miykael_xxm's avatar
Miykael_xxm 已提交
136
### 3.2. Property population
M
Mao 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

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 `with…` method (see below), we use the `with…` method 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. If the property is mutable we set the field directly.

4. If the property is immutable we’re using the constructor to be used by persistence operations (see [Object creation](#mapping.object-creation)) to create a copy of the instance.

5. By default, we set the field value directly.

Property population internals

Similarly to our [optimizations in object construction](#mapping.object-creation.details) 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.lastame);
  }

  void setLastname(String lastname) {
    this.lastname = lastname;
  }
}
```

Example 3. A generated Property Accessor

```
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)
    }
  }
}
```

|**1**|                                                                                        PropertyAccessor’s hold a mutable instance of the underlying object. This is, to enable mutations of otherwise immutable properties.                                                                                        |
|-----|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|                                                                    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.                                                                     |
|**3**|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.|
|**4**|                                                                                                               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.

Let’s have a look at the following entity:

Example 4. A sample entity

```
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, this.age);
  }

  void setRemarks(String remarks) {                                         (5)
    this.remarks = remarks;
  }
}
```

|**1**|The identifier property is final but set to `null` in the constructor.<br/>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.<br/>The original `Person` instance stays unchanged as a new one is created.<br/>The same pattern is usually applied for other properties that are store managed but might have to be changed for persistence operations.<br/>The wither method is optional as the persistence constructor (see 6) is effectively a copy constructor and setting the property will be translated into creating a fresh instance with the new identifier value applied.|
|-----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**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.<br/>With the design shown, the database value will trump the defaulting as Spring Data uses the only declared constructor.<br/>Even if the intent 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 `with…` method 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.<br/>The core idea here is to use factory methods instead of additional constructors to avoid the need for constructor disambiguation through `@PersistenceConstructor`.<br/>Instead, defaulting of properties is handled within the factory method.                                                                                                                                                                                    |

Miykael_xxm's avatar
Miykael_xxm 已提交
273
### 3.3. General recommendations
M
Mao 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

* *Try to stick to immutable objects* — Immutable objects are straightforward 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 co-located types.
  Constructor-only materialization is up to 30% faster than properties population.

* *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 an all-arguments persistence constructor (preferred) or a `with…` method* — 

* *Use Lombok to avoid boilerplate code* — As persistence operations usually require a constructor taking all arguments, their declaration becomes a tedious repetition of boilerplate parameter to field assignments that can best be avoided by using Lombok’s `@AllArgsConstructor`.

Miykael_xxm's avatar
Miykael_xxm 已提交
291
#### 3.3.1. Overriding Properties
M
Mao 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

Java’s allows a flexible design of domain classes where a subclass could define a property that is already declared with the same name in its superclass.
Consider the following example:

```
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);
   }
}
```

Both classes define a `field` using assignable types. `SubType` however shadows `SuperType.field`.
Depending on the class design, using the constructor could be the only default approach to set `SuperType.field`.
Alternatively, calling `super.setField(…)` in the setter could set the `field` in `SuperType`.
All these mechanisms create conflicts to some degree because the properties share the same name yet might represent two distinct values.
Spring Data skips super-type properties if types are not assignable.
That is, the type of the overridden property must be assignable to its super-type property type to be registered as override, otherwise the super-type property is considered transient.
We generally recommend using distinct property names.

Spring Data modules generally support overridden properties holding different values.
From a programming model perspective there are a few things to consider:

1. Which property should be persisted (default to all declared properties)?
   You can exclude properties by annotating these with `@Transient`.

2. How to represent properties in your data store?
   Using the same field/column name for different values typically leads to corrupt data so you should annotate least one of the properties using an explicit field/column name.

3. Using `@AccessType(PROPERTY)` cannot be used as the super-property cannot be generally set without making any further assumptions of the setter implementation.

Miykael_xxm's avatar
Miykael_xxm 已提交
356
### 3.4. Kotlin support
M
Mao 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

Spring Data adapts specifics of Kotlin to allow object creation and mutation.

#### 3.4.1. Kotlin object creation ####

Kotlin classes are supported to be instantiated , all classes are immutable by default and require explicit property declarations to define mutable properties.
Consider the following `data` class `Person`:

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

The class above compiles to a typical class with an explicit constructor.We can customize this class by adding another constructor and annotate it with `@PersistenceConstructor` to indicate a constructor preference:

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

    @PersistenceConstructor
    constructor(id: String) : this(id, "unknown")
}
```

Kotlin supports parameter optionality by allowing default values to be used if a parameter is not provided.
When Spring Data detects a constructor with parameter defaulting, then it leaves these parameters absent if the data store does not provide a value (or simply returns `null`) so Kotlin can apply parameter defaulting.Consider the following class that applies parameter defaulting for `name`

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

Every time the `name` parameter is either not part of the result or its value is `null`, then the `name` defaults to `unknown`.

#### 3.4.2. Property population of Kotlin data classes ####

In Kotlin, all classes are immutable by default and require explicit property declarations to define mutable properties.
Consider the following `data` class `Person`:

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

This class is effectively immutable.
It allows creating new instances as Kotlin generates a `copy(…)` method that creates new object instances copying all property values from the existing object and applying property values provided as arguments to the method.

Miykael_xxm's avatar
Miykael_xxm 已提交
400
#### 3.4.3. Kotlin Overriding Properties
M
Mao 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

Kotlin allows declaring [property overrides](https://kotlinlang.org/docs/inheritance.html#overriding-properties) to alter properties in subclasses.

```
open class SuperType(open var field: Int)

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

Such an arrangement renders two properties with the name `field`.
Kotlin generates property accessors (getters and setters) for each property in each class.
Effectively, the code looks like as follows:

```
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;
   }
}
```

Getters and setters on `SubType` set only `SubType.field` and not `SuperType.field`.
In such an arrangement, using the constructor is the only default approach to set `SuperType.field`.
Adding a method to `SubType` to set `SuperType.field` via `this.SuperType.field = …` is possible but falls outside of supported conventions.
Property overrides create conflicts to some degree because the properties share the same name yet might represent two distinct values.
We generally recommend using distinct property names.

Spring Data modules generally support overridden properties holding different values.
From a programming model perspective there are a few things to consider:

1. Which property should be persisted (default to all declared properties)?
   You can exclude properties by annotating these with `@Transient`.

2. How to represent properties in your data store?
   Using the same field/column name for different values typically leads to corrupt data so you should annotate least one of the properties using an explicit field/column name.

3. Using `@AccessType(PROPERTY)` cannot be used as the super-property cannot be set.

Miykael_xxm's avatar
Miykael_xxm 已提交
470
## 4. Working with Spring Data Repositories
M
Mao 已提交
471 472 473 474 475 476

The goal of the Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

|   |*Spring Data repository documentation and your module*<br/><br/>This chapter explains the core concepts and interfaces of Spring Data repositories.<br/>The information in this chapter is pulled from the Spring Data Commons module.<br/>It uses the configuration and code samples for the Java Persistence API (JPA) module.<br/>You should adapt the XML namespace declaration and the types to be extended to the equivalents of the particular module that you use. “[Namespace reference](#repositories.namespace-reference)” covers XML configuration, which is supported across all Spring Data modules that support the repository API. “[Repository query keywords](#repository-query-keywords)” covers the query method keywords supported by the repository abstraction in general.<br/>For detailed information on the specific features of your module, see the chapter on that module of this document.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
477
### 4.1. Core concepts
M
Mao 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

The central interface in the Spring Data repository abstraction is `Repository`.
It takes the domain class to manage as well as the ID type of the domain class as type arguments.
This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one.
The [`CrudRepository`](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html) interface provides sophisticated CRUD functionality for the entity class that is being managed.

Example 5. `CrudRepository` Interface

```
public interface CrudRepository<T, ID> extends Repository<T, ID> {

  <S extends T> S save(S entity);      (1)

  Optional<T> findById(ID primaryKey); (2)

  Iterable<T> findAll();               (3)

  long count();                        (4)

  void delete(T entity);               (5)

  boolean existsById(ID primaryKey);   (6)

  // … more functionality omitted.
}
```

|**1**|               Saves the given entity.               |
|-----|-----------------------------------------------------|
|**2**|   Returns the entity identified by the given ID.    |
|**3**|                Returns all entities.                |
|**4**|           Returns the number of entities.           |
|**5**|              Deletes the given entity.              |
|**6**|Indicates whether an entity with the given ID exists.|

|   |We also provide persistence technology-specific abstractions, such as `JpaRepository` or `MongoRepository`.<br/>Those interfaces extend `CrudRepository` and expose the capabilities of the underlying persistence technology in addition to the rather generic persistence technology-agnostic interfaces such as `CrudRepository`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

On top of the `CrudRepository`, there is a [`PagingAndSortingRepository`](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html) abstraction that adds additional methods to ease paginated access to entities:

Example 6. `PagingAndSortingRepository` interface

```
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}
```

To access the second page of `User` by a page size of 20, you could do something like the following:

```
PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));
```

In addition to query methods, query derivation for both count and delete queries is available.
The following list shows the interface definition for a derived count query:

Example 7. Derived Count Query

```
interface UserRepository extends CrudRepository<User, Long> {

  long countByLastname(String lastname);
}
```

The following listing shows the interface definition for a derived delete query:

Example 8. Derived Delete Query

```
interface UserRepository extends CrudRepository<User, Long> {

  long deleteByLastname(String lastname);

  List<User> removeByLastname(String lastname);
}
```

Miykael_xxm's avatar
Miykael_xxm 已提交
561
### 4.2. Query Methods
M
Mao 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

Standard CRUD functionality repositories usually have queries on the underlying datastore.
With Spring Data, declaring those queries becomes a four-step process:

1. Declare an interface extending Repository or one of its subinterfaces and type it to the domain class and ID type that it should handle, as shown in the following example:

   ```
   interface PersonRepository extends Repository<Person, Long> { … }
   ```

2. Declare query methods on the interface.

   ```
   interface PersonRepository extends Repository<Person, Long> {
     List<Person> findByLastname(String lastname);
   }
   ```

3. Set up Spring to create proxy instances for those interfaces, either with [JavaConfig](#repositories.create-instances.java-config) or with [XML configuration](#repositories.create-instances).

   1. To use Java configuration, create a class similar to the following:

      ```
      import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

      @EnableJpaRepositories
      class Config { … }
      ```

   2. To use XML configuration, define a bean similar to the following:

      ```
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:jpa="http://www.springframework.org/schema/data/jpa"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/data/jpa
           https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

         <jpa:repositories base-package="com.acme.repositories"/>

      </beans>
      ```

      The JPA namespace is used in this example.
      If you use the repository abstraction for any other store, you need to change this to the appropriate namespace declaration of your store module.
      In other words, you should exchange `jpa` in favor of, for example, `mongodb`.

      Also, note that the JavaConfig variant does not configure a package explicitly, because the package of the annotated class is used by default.
      To customize the package to scan, use one of the `basePackage…` attributes of the data-store-specific repository’s `@Enable${store}Repositories`-annotation.

4. Inject the repository instance and use it, as shown in the following example:

   ```
   class SomeClient {

     private final PersonRepository repository;

     SomeClient(PersonRepository repository) {
       this.repository = repository;
     }

     void doSomething() {
       List<Person> persons = repository.findByLastname("Matthews");
     }
   }
   ```

The sections that follow explain each step in detail:

* [Defining Repository Interfaces](#repositories.definition)

* [Defining Query Methods](#repositories.query-methods.details)

* [Creating Repository Instances](#repositories.create-instances)

* [Custom Implementations for Spring Data Repositories](#repositories.custom-implementations)

Miykael_xxm's avatar
Miykael_xxm 已提交
642
### 4.3. Defining Repository Interfaces
M
Mao 已提交
643 644 645 646 647

To define a repository interface, you first need to define a domain class-specific repository interface.
The interface must extend `Repository` and be typed to the domain class and an ID type.
If you want to expose CRUD methods for that domain type, extend `CrudRepository` instead of `Repository`.

Miykael_xxm's avatar
Miykael_xxm 已提交
648
#### 4.3.1. Fine-tuning Repository Definition
M
Mao 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

Typically, your repository interface extends `Repository`, `CrudRepository`, or `PagingAndSortingRepository`.
Alternatively, if you do not want to extend Spring Data interfaces, you can also annotate your repository interface with `@RepositoryDefinition`.
Extending `CrudRepository` exposes a complete set of methods to manipulate your entities.
If you prefer to be selective about the methods being exposed, copy the methods you want to expose from `CrudRepository` into your domain repository.

|   |Doing so lets you define your own abstractions on top of the provided Spring Data Repositories functionality.|
|---|-------------------------------------------------------------------------------------------------------------|

The following example shows how to selectively expose CRUD methods (`findById` and `save`, in this case):

Example 9. Selectively exposing CRUD methods

```
@NoRepositoryBean
interface MyBaseRepository<T, ID> extends Repository<T, ID> {

  Optional<T> findById(ID id);

  <S extends T> S save(S entity);
}

interface UserRepository extends MyBaseRepository<User, Long> {
  User findByEmailAddress(EmailAddress emailAddress);
}
```

In the prior example, you defined a common base interface for all your domain repositories and exposed `findById(…)` as well as `save(…)`.These methods are routed into the base repository implementation of the store of your choice provided by Spring Data (for example, if you use JPA, the implementation is `SimpleJpaRepository`), because they match the method signatures in `CrudRepository`.
So the `UserRepository` can now save users, find individual users by ID, and trigger a query to find `Users` by email address.

|   |The intermediate repository interface is annotated with `@NoRepositoryBean`.<br/>Make sure you add that annotation to all repository interfaces for which Spring Data should not create instances at runtime.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
682
#### 4.3.2. Using Repositories with Multiple Spring Data Modules
M
Mao 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

Using a unique Spring Data module in your application makes things simple, because all repository interfaces in the defined scope are bound to the Spring Data module.
Sometimes, applications require using more than one Spring Data module.
In such cases, a repository definition must distinguish between persistence technologies.
When it detects multiple repository factories on the class path, Spring Data enters strict repository configuration mode.
Strict configuration uses details on the repository or the domain class to decide about Spring Data module binding for a repository definition:

1. If the repository definition [extends the module-specific repository](#repositories.multiple-modules.types), it is a valid candidate for the particular Spring Data module.

2. If the domain class is [annotated with the module-specific type annotation](#repositories.multiple-modules.annotations), it is a valid candidate for the particular Spring Data module.
   Spring Data modules accept either third-party annotations (such as JPA’s `@Entity`) or provide their own annotations (such as `@Document` for Spring Data MongoDB and Spring Data Elasticsearch).

The following example shows a repository that uses module-specific interfaces (JPA in this case):

Example 10. Repository definitions using module-specific interfaces

```
interface MyRepository extends JpaRepository<User, Long> { }

@NoRepositoryBean
interface MyBaseRepository<T, ID> extends JpaRepository<T, ID> { … }

interface UserRepository extends MyBaseRepository<User, Long> { … }
```

`MyRepository` and `UserRepository` extend `JpaRepository` in their type hierarchy.
They are valid candidates for the Spring Data JPA module.

The following example shows a repository that uses generic interfaces:

Example 11. Repository definitions using generic interfaces

```
interface AmbiguousRepository extends Repository<User, Long> { … }

@NoRepositoryBean
interface MyBaseRepository<T, ID> extends CrudRepository<T, ID> { … }

interface AmbiguousUserRepository extends MyBaseRepository<User, Long> { … }
```

`AmbiguousRepository` and `AmbiguousUserRepository` extend only `Repository` and `CrudRepository` in their type hierarchy.
While this is fine when using a unique Spring Data module, multiple modules cannot distinguish to which particular Spring Data these repositories should be bound.

The following example shows a repository that uses domain classes with annotations:

Example 12. Repository definitions using domain classes with annotations

```
interface PersonRepository extends Repository<Person, Long> { … }

@Entity
class Person { … }

interface UserRepository extends Repository<User, Long> { … }

@Document
class User { … }
```

`PersonRepository` references `Person`, which is annotated with the JPA `@Entity` annotation, so this repository clearly belongs to Spring Data JPA. `UserRepository` references `User`, which is annotated with Spring Data MongoDB’s `@Document` annotation.

The following bad example shows a repository that uses domain classes with mixed annotations:

Example 13. Repository definitions using domain classes with mixed annotations

```
interface JpaPersonRepository extends Repository<Person, Long> { … }

interface MongoDBPersonRepository extends Repository<Person, Long> { … }

@Entity
@Document
class Person { … }
```

This example shows a domain class using both JPA and Spring Data MongoDB annotations.
It defines two repositories, `JpaPersonRepository` and `MongoDBPersonRepository`.
One is intended for JPA and the other for MongoDB usage.
Spring Data is no longer able to tell the repositories apart, which leads to undefined behavior.

[Repository type details](#repositories.multiple-modules.types) and [distinguishing domain class annotations](#repositories.multiple-modules.annotations) are used for strict repository configuration to identify repository candidates for a particular Spring Data module.
Using multiple persistence technology-specific annotations on the same domain type is possible and enables reuse of domain types across multiple persistence technologies.
However, Spring Data can then no longer determine a unique module with which to bind the repository.

The last way to distinguish repositories is by scoping repository base packages.
Base packages define the starting points for scanning for repository interface definitions, which implies having repository definitions located in the appropriate packages.
By default, annotation-driven configuration uses the package of the configuration class.
The [base package in XML-based configuration](#repositories.create-instances.spring) is mandatory.

The following example shows annotation-driven configuration of base packages:

Example 14. Annotation-driven configuration of base packages

```
@EnableJpaRepositories(basePackages = "com.acme.repositories.jpa")
@EnableMongoRepositories(basePackages = "com.acme.repositories.mongo")
class Configuration { … }
```

Miykael_xxm's avatar
Miykael_xxm 已提交
783
### 4.4. Defining Query Methods
M
Mao 已提交
784 785 786 787 788 789 790 791 792 793 794

The repository proxy has two ways to derive a store-specific query from the method name:

* By deriving the query from the method name directly.

* By using a manually defined query.

Available options depend on the actual store.
However, there must be a strategy that decides what actual query is created.
The next section describes the available options.

Miykael_xxm's avatar
Miykael_xxm 已提交
795
#### 4.4.1. Query Lookup Strategies
M
Mao 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

The following strategies are available for the repository infrastructure to resolve the query.
With XML configuration, you can configure the strategy at the namespace through the `query-lookup-strategy` attribute.
For Java configuration, you can use the `queryLookupStrategy` attribute of the `Enable${store}Repositories` annotation.
Some strategies may not be supported for particular datastores.

* `CREATE` attempts to construct a store-specific query from the query method name.
  The general approach is to remove a given set of well known prefixes from the method name and parse the rest of the method.
  You can read more about query construction in “[Query Creation](#repositories.query-methods.query-creation)”.

* `USE_DECLARED_QUERY` tries to find a declared query and throws an exception if it cannot find one.
  The query can be defined by an annotation somewhere or declared by other means.
  See the documentation of the specific store to find available options for that store.
  If the repository infrastructure does not find a declared query for the method at bootstrap time, it fails.

* `CREATE_IF_NOT_FOUND` (the default) combines `CREATE` and `USE_DECLARED_QUERY`.
  It looks up a declared query first, and, if no declared query is found, it creates a custom method name-based query.
  This is the default lookup strategy and, thus, is used if you do not configure anything explicitly.
  It allows quick query definition by method names but also custom-tuning of these queries by introducing declared queries as needed.

Miykael_xxm's avatar
Miykael_xxm 已提交
816
#### 4.4.2. Query Creation
M
Mao 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

The query builder mechanism built into the Spring Data repository infrastructure is useful for building constraining queries over entities of the repository.

The following example shows how to create a number of queries:

Example 15. Query creation from method names

```
interface PersonRepository extends Repository<Person, Long> {

  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

  // Enables the distinct flag for the query
  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
  List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

  // Enabling ignoring case for an individual property
  List<Person> findByLastnameIgnoreCase(String lastname);
  // Enabling ignoring case for all suitable properties
  List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

  // Enabling static ORDER BY for a query
  List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
  List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}
```

Parsing query method names is divided into subject and predicate.
The first part (`find…By`, `exists…By`) defines the subject of the query, the second part forms the predicate.
The introducing clause (subject) can contain further expressions.
Any text between `find` (or other introducing keywords) and `By` is considered to be descriptive unless using one of the result-limiting keywords such as a `Distinct` to set a distinct flag on the query to be created or [`Top`/`First` to limit query results](#repositories.limit-query-result).

The appendix contains the [full list of query method subject keywords](#appendix.query.method.subject) and [query method predicate keywords including sorting and letter-casing modifiers](#appendix.query.method.predicate).
However, the first `By` acts as a delimiter to indicate the start of the actual criteria predicate.
At a very basic level, you can define conditions on entity properties and concatenate them with `And` and `Or`.

The actual result of parsing the method depends on the persistence store for which you create the query.
However, there are some general things to notice:

* The expressions are usually property traversals combined with operators that can be concatenated.
  You can combine property expressions with `AND` and `OR`.
  You also get support for operators such as `Between`, `LessThan`, `GreaterThan`, and `Like` for the property expressions.
  The supported operators can vary by datastore, so consult the appropriate part of your reference documentation.

* The method parser supports setting an `IgnoreCase` flag for individual properties (for example, `findByLastnameIgnoreCase(…)`) or for all properties of a type that supports ignoring case (usually `String` instances — for example, `findByLastnameAndFirstnameAllIgnoreCase(…)`).
  Whether ignoring cases is supported may vary by store, so consult the relevant sections in the reference documentation for the store-specific query method.

* You can apply static ordering by appending an `OrderBy` clause to the query method that references a property and by providing a sorting direction (`Asc` or `Desc`).
  To create a query method that supports dynamic sorting, see “[Special parameter handling](#repositories.special-parameters)”.

Miykael_xxm's avatar
Miykael_xxm 已提交
867
#### 4.4.3. Property Expressions
M
Mao 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898

Property expressions can refer only to a direct property of the managed entity, as shown in the preceding example.
At query creation time, you already make sure that the parsed property is a property of the managed domain class.
However, you can also define constraints by traversing nested properties.
Consider the following method signature:

```
List<Person> findByAddressZipCode(ZipCode zipCode);
```

Assume a `Person` has an `Address` with a `ZipCode`.
In that case, the method creates the `x.address.zipCode` property traversal.
The resolution algorithm starts by interpreting the entire part (`AddressZipCode`) as the property and checks the domain class for a property with that name (uncapitalized).
If the algorithm succeeds, it uses that property.
If not, the algorithm splits up the source at the camel-case parts from the right side into a head and a tail and tries to find the corresponding property — in our example, `AddressZip` and `Code`.
If the algorithm finds a property with that head, it takes the tail and continues building the tree down from there, splitting the tail up in the way just described.
If the first split does not match, the algorithm moves the split point to the left (`Address`, `ZipCode`) and continues.

Although this should work for most cases, it is possible for the algorithm to select the wrong property.
Suppose the `Person` class has an `addressZip` property as well.
The algorithm would match in the first split round already, choose the wrong property, and fail (as the type of `addressZip` probably has no `code` property).

To resolve this ambiguity you can use `_` inside your method name to manually define traversal points.
So our method name would be as follows:

```
List<Person> findByAddress_ZipCode(ZipCode zipCode);
```

Because we treat the underscore character as a reserved character, we strongly advise following standard Java naming conventions (that is, not using underscores in property names but using camel case instead).

Miykael_xxm's avatar
Miykael_xxm 已提交
899
#### 4.4.4. Special parameter handling
M
Mao 已提交
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934

To handle parameters in your query, define method parameters as already seen in the preceding examples.
Besides that, the infrastructure recognizes certain specific types like `Pageable` and `Sort`, to apply pagination and sorting to your queries dynamically.
The following example demonstrates these features:

Example 16. Using `Pageable`, `Slice`, and `Sort` in query methods

```
Page<User> findByLastname(String lastname, Pageable pageable);

Slice<User> findByLastname(String lastname, Pageable pageable);

List<User> findByLastname(String lastname, Sort sort);

List<User> findByLastname(String lastname, Pageable pageable);
```

|   |APIs taking `Sort` and `Pageable` expect non-`null` values to be handed into methods.<br/>If you do not want to apply any sorting or pagination, use `Sort.unsorted()` and `Pageable.unpaged()`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The first method lets you pass an `org.springframework.data.domain.Pageable` instance to the query method to dynamically add paging to your statically defined query.
A `Page` knows about the total number of elements and pages available.
It does so by the infrastructure triggering a count query to calculate the overall number.
As this might be expensive (depending on the store used), you can instead return a `Slice`.
A `Slice` knows only about whether a next `Slice` is available, which might be sufficient when walking through a larger result set.

Sorting options are handled through the `Pageable` instance, too.
If you need only sorting, add an `org.springframework.data.domain.Sort` parameter to your method.
As you can see, returning a `List` is also possible.
In this case, the additional metadata required to build the actual `Page` instance is not created (which, in turn, means that the additional count query that would have been necessary is not issued).
Rather, it restricts the query to look up only the given range of entities.

|   |To find out how many pages you get for an entire query, you have to trigger an additional count query.<br/>By default, this query is derived from the query you actually trigger.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
935
##### Paging and Sorting
M
Mao 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969

You can define simple sorting expressions by using property names.
You can concatenate expressions to collect multiple criteria into one expression.

Example 17. Defining sort expressions

```
Sort sort = Sort.by("firstname").ascending()
  .and(Sort.by("lastname").descending());
```

For a more type-safe way to define sort expressions, start with the type for which to define the sort expression and use method references to define the properties on which to sort.

Example 18. Defining sort expressions by using the type-safe API

```
TypedSort<Person> person = Sort.sort(Person.class);

Sort sort = person.by(Person::getFirstname).ascending()
  .and(person.by(Person::getLastname).descending());
```

|   |`TypedSort.by(…)` makes use of runtime proxies by (typically) using CGlib, which may interfere with native image compilation when using tools such as Graal VM Native.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|

If your store implementation supports Querydsl, you can also use the generated metamodel types to define sort expressions:

Example 19. Defining sort expressions by using the Querydsl API

```
QSort sort = QSort.by(QPerson.firstname.asc())
  .and(QSort.by(QPerson.lastname.desc()));
```

Miykael_xxm's avatar
Miykael_xxm 已提交
970
#### 4.4.5. Limiting Query Results
M
Mao 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000

You can limit the results of query methods by using the `first` or `top` keywords, which you can use interchangeably.
You can append an optional numeric value to `top` or `first` to specify the maximum result size to be returned.
If the number is left out, a result size of 1 is assumed.
The following example shows how to limit the query size:

Example 20. Limiting the result size of a query with `Top` and `First`

```
User findFirstByOrderByLastnameAsc();

User findTopByOrderByAgeDesc();

Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

Slice<User> findTop3ByLastname(String lastname, Pageable pageable);

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);
```

The limiting expressions also support the `Distinct` keyword for datastores that support distinct queries.
Also, for the queries that limit the result set to one instance, wrapping the result into with the `Optional` keyword is supported.

If pagination or slicing is applied to a limiting query pagination (and the calculation of the number of available pages), it is applied within the limited result.

|   |Limiting the results in combination with dynamic sorting by using a `Sort` parameter lets you express query methods for the 'K' smallest as well as for the 'K' biggest elements.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
1001
#### 4.4.6. Repository Methods Returning Collections or Iterables
M
Mao 已提交
1002 1003 1004 1005 1006

Query methods that return multiple results can use standard Java `Iterable`, `List`, and `Set`.
Beyond that, we support returning Spring Data’s `Streamable`, a custom extension of `Iterable`, as well as collection types provided by [Vavr](https://www.vavr.io/).
Refer to the appendix explaining all possible [query method return types](#appendix.query.return.types).

Miykael_xxm's avatar
Miykael_xxm 已提交
1007
##### Using Streamable as Query Method Return Type
M
Mao 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

You can use `Streamable` as alternative to `Iterable` or any collection type.
It provides convenience methods to access a non-parallel `Stream` (missing from `Iterable`) and the ability to directly `….filter(…)` and `….map(…)` over the elements and concatenate the `Streamable` to others:

Example 21. Using Streamable to combine query method results

```
interface PersonRepository extends Repository<Person, Long> {
  Streamable<Person> findByFirstnameContaining(String firstname);
  Streamable<Person> findByLastnameContaining(String lastname);
}

Streamable<Person> result = repository.findByFirstnameContaining("av")
  .and(repository.findByLastnameContaining("ea"));
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1024
##### Returning Custom Streamable Wrapper Types
M
Mao 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

Providing dedicated wrapper types for collections is a commonly used pattern to provide an API for a query result that returns multiple elements.
Usually, these types are used by invoking a repository method returning a collection-like type and creating an instance of the wrapper type manually.
You can avoid that additional step as Spring Data lets you use these wrapper types as query method return types if they meet the following criteria:

1. The type implements `Streamable`.

2. The type exposes either a constructor or a static factory method named `of(…)` or `valueOf(…)` that takes `Streamable` as an argument.

The following listing shows an example:

```
class Product {                                         (1)
  MonetaryAmount getPrice() { … }
}

@RequiredArgsConstructor(staticName = "of")
class Products implements Streamable<Product> {         (2)

  private final Streamable<Product> streamable;

  public MonetaryAmount getTotal() {                    (3)
    return streamable.stream()
      .map(Priced::getPrice)
      .reduce(Money.of(0), MonetaryAmount::add);
  }

  @Override
  public Iterator<Product> iterator() {                 (4)
    return streamable.iterator();
  }
}

interface ProductRepository implements Repository<Product, Long> {
  Products findAllByDescriptionContaining(String text); (5)
}
```

|**1**|                                                                              A `Product` entity that exposes API to access the product’s price.                                                                              |
|-----|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|A wrapper type for a `Streamable<Product>` that can be constructed by using `Products.of(…)` (factory method created with the Lombok annotation).<br/>A standard constructor taking the `Streamable<Product>` will do as well.|
|**3**|                                                               The wrapper type exposes an additional API, calculating new values on the `Streamable<Product>`.                                                               |
|**4**|                                                                           Implement the `Streamable` interface and delegate to the actual result.                                                                            |
|**5**|             That wrapper type `Products` can be used directly as a query method return type.<br/>You do not need to return `Streamable<Product>` and manually wrap it after the query in the repository client.              |

Miykael_xxm's avatar
Miykael_xxm 已提交
1070
##### Support for Vavr Collections
M
Mao 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

[Vavr](https://www.vavr.io/) is a library that embraces functional programming concepts in Java.
It ships with a custom set of collection types that you can use as query method return types, as the following table shows:

|  Vavr collection type  |  Used Vavr implementation type   |Valid Java source types|
|------------------------|----------------------------------|-----------------------|
|`io.vavr.collection.Seq`|    `io.vavr.collection.List`     | `java.util.Iterable`  |
|`io.vavr.collection.Set`|`io.vavr.collection.LinkedHashSet`| `java.util.Iterable`  |
|`io.vavr.collection.Map`|`io.vavr.collection.LinkedHashMap`|    `java.util.Map`    |

You can use the types in the first column (or subtypes thereof) as query method return types and get the types in the second column used as implementation type, depending on the Java type of the actual query result (third column).
Alternatively, you can declare `Traversable` (the Vavr `Iterable` equivalent), and we then derive the implementation class from the actual return value.
That is, a `java.util.List` is turned into a Vavr `List` or `Seq`, a `java.util.Set` becomes a Vavr `LinkedHashSet` `Set`, and so on.

Miykael_xxm's avatar
Miykael_xxm 已提交
1085
#### 4.4.7. Null Handling of Repository Methods
M
Mao 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

As of Spring Data 2.0, repository CRUD methods that return an individual aggregate instance use Java 8’s `Optional` to indicate the potential absence of a value.
Besides that, Spring Data supports returning the following wrapper types on query methods:

* `com.google.common.base.Optional`

* `scala.Option`

* `io.vavr.control.Option`

Alternatively, query methods can choose not to use a wrapper type at all.
The absence of a query result is then indicated by returning `null`.
Repository methods returning collections, collection alternatives, wrappers, and streams are guaranteed never to return `null` but rather the corresponding empty representation.
See “[Repository query return types](#repository-query-return-types)” for details.

Miykael_xxm's avatar
Miykael_xxm 已提交
1101
##### Nullability Annotations
M
Mao 已提交
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

You can express nullability constraints for repository methods by using [Spring Framework’s nullability annotations](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#null-safety).
They provide a tooling-friendly approach and opt-in `null` checks during runtime, as follows:

* [`@NonNullApi`](https://docs.spring.io/spring/docs/5.3.16/javadoc-api/org/springframework/lang/NonNullApi.html): Used on the package level to declare that the default behavior for parameters and return values is, respectively, neither to accept nor to produce `null` values.

* [`@NonNull`](https://docs.spring.io/spring/docs/5.3.16/javadoc-api/org/springframework/lang/NonNull.html): Used on a parameter or return value that must not be `null` (not needed on a parameter and return value where `@NonNullApi` applies).

* [`@Nullable`](https://docs.spring.io/spring/docs/5.3.16/javadoc-api/org/springframework/lang/Nullable.html): Used on a parameter or return value that can be `null`.

Spring annotations are meta-annotated with [JSR 305](https://jcp.org/en/jsr/detail?id=305) annotations (a dormant but widely used JSR).
JSR 305 meta-annotations let tooling vendors (such as [IDEA](https://www.jetbrains.com/help/idea/nullable-and-notnull-annotations.html), [Eclipse](https://help.eclipse.org/oxygen/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/task-using_external_null_annotations.htm), and [Kotlin](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types)) provide null-safety support in a generic way, without having to hard-code support for Spring annotations.
To enable runtime checking of nullability constraints for query methods, you need to activate non-nullability on the package level by using Spring’s `@NonNullApi` in `package-info.java`, as shown in the following example:

Example 22. Declaring Non-nullability in `package-info.java`

```
@org.springframework.lang.NonNullApi
package com.acme;
```

Once non-null defaulting is in place, repository query method invocations get validated at runtime for nullability constraints.
If a query result violates the defined constraint, an exception is thrown.
This happens when the method would return `null` but is declared as non-nullable (the default with the annotation defined on the package in which the repository resides).
If you want to opt-in to nullable results again, selectively use `@Nullable` on individual methods.
Using the result wrapper types mentioned at the start of this section continues to work as expected: an empty result is translated into the value that represents absence.

The following example shows a number of the techniques just described:

Example 23. Using different nullability constraints

```
package com.acme;                                                       (1)

import org.springframework.lang.Nullable;

interface UserRepository extends Repository<User, Long> {

  User getByEmailAddress(EmailAddress emailAddress);                    (2)

  @Nullable
  User findByEmailAddress(@Nullable EmailAddress emailAdress);          (3)

  Optional<User> findOptionalByEmailAddress(EmailAddress emailAddress); (4)
}
```

|**1**|                                          The repository resides in a package (or sub-package) for which we have defined non-null behavior.                                          |
|-----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|Throws an `EmptyResultDataAccessException` when the query does not produce a result.<br/>Throws an `IllegalArgumentException` when the `emailAddress` handed to the method is `null`.|
|**3**|                                  Returns `null` when the query does not produce a result.<br/>Also accepts `null` as the value for `emailAddress`.                                  |
|**4**|        Returns `Optional.empty()` when the query does not produce a result.<br/>Throws an `IllegalArgumentException` when the `emailAddress` handed to the method is `null`.        |

Miykael_xxm's avatar
Miykael_xxm 已提交
1155
##### Nullability in Kotlin-based Repositories
M
Mao 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176

Kotlin has the definition of [nullability constraints](https://kotlinlang.org/docs/reference/null-safety.html) baked into the language.
Kotlin code compiles to bytecode, which does not express nullability constraints through method signatures but rather through compiled-in metadata.
Make sure to include the `kotlin-reflect` JAR in your project to enable introspection of Kotlin’s nullability constraints.
Spring Data repositories use the language mechanism to define those constraints to apply the same runtime checks, as follows:

Example 24. Using nullability constraints on Kotlin repositories

```
interface UserRepository : Repository<User, String> {

  fun findByUsername(username: String): User     (1)

  fun findByFirstname(firstname: String?): User? (2)
}
```

|**1**|The method defines both the parameter and the result as non-nullable (the Kotlin default).<br/>The Kotlin compiler rejects method invocations that pass `null` to the method.<br/>If the query yields an empty result, an `EmptyResultDataAccessException` is thrown.|
|-----|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|                                                                         This method accepts `null` for the `firstname` parameter and returns `null` if the query does not produce a result.                                                                         |

Miykael_xxm's avatar
Miykael_xxm 已提交
1177
#### 4.4.8. Streaming Query Results
M
Mao 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

You can process the results of query methods incrementally by using a Java 8 `Stream<T>` as the return type.
Instead of wrapping the query results in a `Stream`, data store-specific methods are used to perform the streaming, as shown in the following example:

Example 25. Stream the result of a query with Java 8 `Stream<T>`

```
@Query("select u from User u")
Stream<User> findAllByCustomQueryAndStream();

Stream<User> readAllByFirstnameNotNull();

@Query("select u from User u")
Stream<User> streamAllPaged(Pageable pageable);
```

|   |A `Stream` potentially wraps underlying data store-specific resources and must, therefore, be closed after usage.<br/>You can either manually close the `Stream` by using the `close()` method or by using a Java 7 `try-with-resources` block, as shown in the following example:|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Example 26. Working with a `Stream<T>` result in a `try-with-resources` block

```
try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
  stream.forEach(…);
}
```

|   |Not all Spring Data modules currently support `Stream<T>` as a return type.|
|---|---------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
1208
#### 4.4.9. Asynchronous Query Results
M
Mao 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231

You can run repository queries asynchronously by using [Spring’s asynchronous method running capability](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/integration.html#scheduling).
This means the method returns immediately upon invocation while the actual query occurs in a task that has been submitted to a Spring `TaskExecutor`.
Asynchronous queries differ from reactive queries and should not be mixed.
See the store-specific documentation for more details on reactive support.
The following example shows a number of asynchronous queries:

```
@Async
Future<User> findByFirstname(String firstname);               (1)

@Async
CompletableFuture<User> findOneByFirstname(String firstname); (2)

@Async
ListenableFuture<User> findOneByLastname(String lastname);    (3)
```

|**1**|             Use `java.util.concurrent.Future` as the return type.              |
|-----|--------------------------------------------------------------------------------|
|**2**|   Use a Java 8 `java.util.concurrent.CompletableFuture` as the return type.    |
|**3**|Use a `org.springframework.util.concurrent.ListenableFuture` as the return type.|

Miykael_xxm's avatar
Miykael_xxm 已提交
1232
### 4.5. Creating Repository Instances
M
Mao 已提交
1233 1234 1235

This section covers how to create instances and bean definitions for the defined repository interfaces. One way to do so is by using the Spring namespace that is shipped with each Spring Data module that supports the repository mechanism, although we generally recommend using Java configuration.

Miykael_xxm's avatar
Miykael_xxm 已提交
1236
#### 4.5.1. XML Configuration
M
Mao 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262

Each Spring Data module includes a `repositories` element that lets you define a base package that Spring scans for you, as shown in the following example:

Example 27. Enabling Spring Data repositories via XML

```
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <repositories base-package="com.acme.repositories" />

</beans:beans>
```

In the preceding example, Spring is instructed to scan `com.acme.repositories` and all its sub-packages for interfaces extending `Repository` or one of its sub-interfaces.
For each interface found, the infrastructure registers the persistence technology-specific `FactoryBean` to create the appropriate proxies that handle invocations of the query methods.
Each bean is registered under a bean name that is derived from the interface name, so an interface of `UserRepository` would be registered under `userRepository`.
Bean names for nested repository interfaces are prefixed with their enclosing type name.
The `base-package` attribute allows wildcards so that you can define a pattern of scanned packages.

Miykael_xxm's avatar
Miykael_xxm 已提交
1263
##### Using Filters
M
Mao 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

By default, the infrastructure picks up every interface that extends the persistence technology-specific `Repository` sub-interface located under the configured base package and creates a bean instance for it.
However, you might want more fine-grained control over which interfaces have bean instances created for them.
To do so, use `<include-filter />` and `<exclude-filter />` elements inside the `<repositories />` element.
The semantics are exactly equivalent to the elements in Spring’s context namespace.
For details, see the [Spring reference documentation](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#beans-scanning-filters) for these elements.

For example, to exclude certain interfaces from instantiation as repository beans, you could use the following configuration:

Example 28. Using exclude-filter element

```
<repositories base-package="com.acme.repositories">
  <context:exclude-filter type="regex" expression=".*SomeRepository" />
</repositories>
```

The preceding example excludes all interfaces ending in `SomeRepository` from being instantiated.

Miykael_xxm's avatar
Miykael_xxm 已提交
1283
#### 4.5.2. Java Configuration
M
Mao 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305

You can also trigger the repository infrastructure by using a store-specific `@Enable${store}Repositories` annotation on a Java configuration class. For an introduction to Java-based configuration of the Spring container, see [JavaConfig in the Spring reference documentation](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#beans-java).

A sample configuration to enable Spring Data repositories resembles the following:

Example 29. Sample annotation-based repository configuration

```
@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {

  @Bean
  EntityManagerFactory entityManagerFactory() {
    // …
  }
}
```

|   |The preceding example uses the JPA-specific annotation, which you would change according to the store module you actually use. The same applies to the definition of the `EntityManagerFactory` bean. See the sections covering the store-specific configuration.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
1306
#### 4.5.3. Standalone Usage
M
Mao 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

You can also use the repository infrastructure outside of a Spring container — for example, in CDI environments. You still need some Spring libraries in your classpath, but, generally, you can set up repositories programmatically as well. The Spring Data modules that provide repository support ship with a persistence technology-specific `RepositoryFactory` that you can use, as follows:

Example 30. Standalone usage of the repository factory

```
RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1317
### 4.6. Custom Implementations for Spring Data Repositories
M
Mao 已提交
1318 1319 1320 1321 1322

Spring Data provides various options to create query methods with little coding.
But when those options don’t fit your needs you can also provide your own custom implementation for repository methods.
This section describes how to do that.

Miykael_xxm's avatar
Miykael_xxm 已提交
1323
#### 4.6.1. Customizing Individual Repositories
M
Mao 已提交
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442

To enrich a repository with custom functionality, you must first define a fragment interface and an implementation for the custom functionality, as follows:

Example 31. Interface for custom repository functionality

```
interface CustomizedUserRepository {
  void someCustomMethod(User user);
}
```

Example 32. Implementation of custom repository functionality

```
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}
```

|   |The most important part of the class name that corresponds to the fragment interface is the `Impl` postfix.|
|---|-----------------------------------------------------------------------------------------------------------|

The implementation itself does not depend on Spring Data and can be a regular Spring bean.Consequently, you can use standard dependency injection behavior to inject references to other beans (such as a `JdbcTemplate`), take part in aspects, and so on.

Then you can let your repository interface extend the fragment interface, as follows:

Example 33. Changes to your repository interface

```
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

  // Declare query methods here
}
```

Extending the fragment interface with your repository interface combines the CRUD and custom functionality and makes it available to clients.

Spring Data repositories are implemented by using fragments that form a repository composition. Fragments are the base repository, functional aspects (such as [QueryDsl](#core.extensions.querydsl)), and custom interfaces along with their implementations. Each time you add an interface to your repository interface, you enhance the composition by adding a fragment. The base repository and repository aspect implementations are provided by each Spring Data module.

The following example shows custom interfaces and their implementations:

Example 34. Fragments with their implementations

```
interface HumanRepository {
  void someHumanMethod(User user);
}

class HumanRepositoryImpl implements HumanRepository {

  public void someHumanMethod(User user) {
    // Your custom implementation
  }
}

interface ContactRepository {

  void someContactMethod(User user);

  User anotherContactMethod(User user);
}

class ContactRepositoryImpl implements ContactRepository {

  public void someContactMethod(User user) {
    // Your custom implementation
  }

  public User anotherContactMethod(User user) {
    // Your custom implementation
  }
}
```

The following example shows the interface for a custom repository that extends `CrudRepository`:

Example 35. Changes to your repository interface

```
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {

  // Declare query methods here
}
```

Repositories may be composed of multiple custom implementations that are imported in the order of their declaration. Custom implementations have a higher priority than the base implementation and repository aspects. This ordering lets you override base repository and aspect methods and resolves ambiguity if two fragments contribute the same method signature. Repository fragments are not limited to use in a single repository interface. Multiple repositories may use a fragment interface, letting you reuse customizations across different repositories.

The following example shows a repository fragment and its implementation:

Example 36. Fragments overriding `save(…)`

```
interface CustomizedSave<T> {
  <S extends T> S save(S entity);
}

class CustomizedSaveImpl<T> implements CustomizedSave<T> {

  public <S extends T> S save(S entity) {
    // Your custom implementation
  }
}
```

The following example shows a repository that uses the preceding repository fragment:

Example 37. Customized repository interfaces

```
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}

interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1443
##### Configuration
M
Mao 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460

If you use namespace configuration, the repository infrastructure tries to autodetect custom implementation fragments by scanning for classes below the package in which it found a repository.
These classes need to follow the naming convention of appending the namespace element’s `repository-impl-postfix` attribute to the fragment interface name.
This postfix defaults to `Impl`.
The following example shows a repository that uses the default postfix and a repository that sets a custom value for the postfix:

Example 38. Configuration example

```
<repositories base-package="com.acme.repository" />

<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />
```

The first configuration in the preceding example tries to look up a class called `com.acme.repository.CustomizedUserRepositoryImpl` to act as a custom repository implementation.
The second example tries to look up `com.acme.repository.CustomizedUserRepositoryMyPostfix`.

Miykael_xxm's avatar
Miykael_xxm 已提交
1461
###### Resolution of Ambiguity
M
Mao 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490

If multiple implementations with matching class names are found in different packages, Spring Data uses the bean names to identify which one to use.

Given the following two custom implementations for the `CustomizedUserRepository` shown earlier, the first implementation is used.
Its bean name is `customizedUserRepositoryImpl`, which matches that of the fragment interface (`CustomizedUserRepository`) plus the postfix `Impl`.

Example 39. Resolution of ambiguous implementations

```
package com.acme.impl.one;

class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}
```

```
package com.acme.impl.two;

@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}
```

If you annotate the `UserRepository` interface with `@Component("specialCustom")`, the bean name plus `Impl` then matches the one defined for the repository implementation in `com.acme.impl.two`, and it is used instead of the first one.

Miykael_xxm's avatar
Miykael_xxm 已提交
1491
###### Manual Wiring
M
Mao 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

If your custom implementation uses annotation-based configuration and autowiring only, the preceding approach shown works well, because it is treated as any other Spring bean.
If your implementation fragment bean needs special wiring, you can declare the bean and name it according to the conventions described in the [preceding section](#repositories.single-repository-behaviour.ambiguity).
The infrastructure then refers to the manually defined bean definition by name instead of creating one itself.
The following example shows how to manually wire a custom implementation:

Example 40. Manual wiring of custom implementations

```
<repositories base-package="com.acme.repository" />

<beans:bean id="userRepositoryImpl" class="…">
  <!-- further configuration -->
</beans:bean>
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1508
#### 4.6.2. Customize the Base Repository
M
Mao 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

The approach described in the [preceding section](#repositories.manual-wiring) requires customization of each repository interfaces when you want to customize the base repository behavior so that all repositories are affected.
To instead change behavior for all repositories, you can create an implementation that extends the persistence technology-specific repository base class.
This class then acts as a custom base class for the repository proxies, as shown in the following example:

Example 41. Custom repository base class

```
class MyRepositoryImpl<T, ID>
  extends SimpleJpaRepository<T, ID> {

  private final EntityManager entityManager;

  MyRepositoryImpl(JpaEntityInformation entityInformation,
                          EntityManager entityManager) {
    super(entityInformation, entityManager);

    // Keep the EntityManager around to used from the newly introduced methods.
    this.entityManager = entityManager;
  }

  @Transactional
  public <S extends T> S save(S entity) {
    // implementation goes here
  }
}
```

|   |The class needs to have a constructor of the super class which the store-specific repository factory implementation uses.<br/>If the repository base class has multiple constructors, override the one taking an `EntityInformation` plus a store specific infrastructure object (such as an `EntityManager` or a template class).|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The final step is to make the Spring Data infrastructure aware of the customized repository base class.
In Java configuration, you can do so by using the `repositoryBaseClass` attribute of the `@Enable${store}Repositories` annotation, as shown in the following example:

Example 42. Configuring a custom repository base class using JavaConfig

```
@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
```

A corresponding attribute is available in the XML namespace, as shown in the following example:

Example 43. Configuring a custom repository base class using XML

```
<repositories base-package="com.acme.repository"
     base-class="….MyRepositoryImpl" />
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1560
### 4.7. Publishing Events from Aggregate Roots
M
Mao 已提交
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

Entities managed by repositories are aggregate roots.
In a Domain-Driven Design application, these aggregate roots usually publish domain events.
Spring Data provides an annotation called `@DomainEvents` that you can use on a method of your aggregate root to make that publication as easy as possible, as shown in the following example:

Example 44. Exposing domain events from an aggregate root

```
class AnAggregateRoot {

    @DomainEvents (1)
    Collection<Object> domainEvents() {
        // … return events you want to get published here
    }

    @AfterDomainEventPublication (2)
    void callbackMethod() {
       // … potentially clean up domain events list
    }
}
```

|**1**|                           The method that uses `@DomainEvents` can return either a single event instance or a collection of events.<br/>It must not take any arguments.                            |
|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|After all events have been published, we have a method annotated with `@AfterDomainEventPublication`.<br/>You can use it to potentially clean the list of events to be published (among other uses).|

The methods are called every time one of a Spring Data repository’s `save(…)`, `saveAll(…)`, `delete(…)` or `deleteAll(…)` methods are called.

Miykael_xxm's avatar
Miykael_xxm 已提交
1589
### 4.8. Spring Data Extensions
M
Mao 已提交
1590 1591 1592 1593

This section documents a set of Spring Data extensions that enable Spring Data usage in a variety of contexts.
Currently, most of the integration is targeted towards Spring MVC.

Miykael_xxm's avatar
Miykael_xxm 已提交
1594
#### 4.8.1. Querydsl Extension
M
Mao 已提交
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640

[Querydsl](http://www.querydsl.com/) is a framework that enables the construction of statically typed SQL-like queries through its fluent API.

Several Spring Data modules offer integration with Querydsl through `QuerydslPredicateExecutor`, as the following example shows:

Example 45. QuerydslPredicateExecutor interface

```
public interface QuerydslPredicateExecutor<T> {

  Optional<T> findById(Predicate predicate);  (1)

  Iterable<T> findAll(Predicate predicate);   (2)

  long count(Predicate predicate);            (3)

  boolean exists(Predicate predicate);        (4)

  // … more functionality omitted.
}
```

|**1**| Finds and returns a single entity matching the `Predicate`.  |
|-----|--------------------------------------------------------------|
|**2**|   Finds and returns all entities matching the `Predicate`.   |
|**3**|   Returns the number of entities matching the `Predicate`.   |
|**4**|Returns whether an entity that matches the `Predicate` exists.|

To use the Querydsl support, extend `QuerydslPredicateExecutor` on your repository interface, as the following example shows:

Example 46. Querydsl integration on repositories

```
interface UserRepository extends CrudRepository<User, Long>, QuerydslPredicateExecutor<User> {
}
```

The preceding example lets you write type-safe queries by using Querydsl `Predicate` instances, as the following example shows:

```
Predicate predicate = user.firstname.equalsIgnoreCase("dave")
	.and(user.lastname.startsWithIgnoreCase("mathews"));

userRepository.findAll(predicate);
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1641
#### 4.8.2. Web support
M
Mao 已提交
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671

Spring Data modules that support the repository programming model ship with a variety of web support.
The web related components require Spring MVC JARs to be on the classpath.
Some of them even provide integration with [Spring HATEOAS](https://github.com/spring-projects/spring-hateoas).
In general, the integration support is enabled by using the `@EnableSpringDataWebSupport` annotation in your JavaConfig configuration class, as the following example shows:

Example 47. Enabling Spring Data web support

```
@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
class WebConfiguration {}
```

The `@EnableSpringDataWebSupport` annotation registers a few components.
We discuss those later in this section.
It also detects Spring HATEOAS on the classpath and registers integration components (if present) for it as well.

Alternatively, if you use XML configuration, register either `SpringDataWebConfiguration` or `HateoasAwareSpringDataWebConfiguration` as Spring beans, as the following example shows (for `SpringDataWebConfiguration`):

Example 48. Enabling Spring Data web support in XML

```
<bean class="org.springframework.data.web.config.SpringDataWebConfiguration" />

<!-- If you use Spring HATEOAS, register this one *instead* of the former -->
<bean class="org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration" />
```

Miykael_xxm's avatar
Miykael_xxm 已提交
1672
##### Basic Web Support
M
Mao 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681

The configuration shown in the [previous section](#core.web) registers a few basic components:

* A [Using the `DomainClassConverter` Class](#core.web.basic.domain-class-converter) to let Spring MVC resolve instances of repository-managed domain classes from request parameters or path variables.

* [`HandlerMethodArgumentResolver`](#core.web.basic.paging-and-sorting) implementations to let Spring MVC resolve `Pageable` and `Sort` instances from request parameters.

* [Jackson Modules](#core.web.basic.jackson-mappers) to de-/serialize types like `Point` and `Distance`, or store specific ones, depending on the Spring Data Module used.

Miykael_xxm's avatar
Miykael_xxm 已提交
1682
###### Using the `DomainClassConverter` Class
M
Mao 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707

The `DomainClassConverter` class lets you use domain types in your Spring MVC controller method signatures directly so that you need not manually lookup the instances through the repository, as the following example shows:

Example 49. A Spring MVC controller using domain types in method signatures

```
@Controller
@RequestMapping("/users")
class UserController {

  @RequestMapping("/{id}")
  String showUserForm(@PathVariable("id") User user, Model model) {

    model.addAttribute("user", user);
    return "userForm";
  }
}
```

The method receives a `User` instance directly, and no further lookup is necessary.
The instance can be resolved by letting Spring MVC convert the path variable into the `id` type of the domain class first and eventually access the instance through calling `findById(…)` on the repository instance registered for the domain type.

|   |Currently, the repository has to implement `CrudRepository` to be eligible to be discovered for conversion.|
|---|-----------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
1708
###### HandlerMethodArgumentResolvers for Pageable and Sort
M
Mao 已提交
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

The configuration snippet shown in the [previous section](#core.web.basic.domain-class-converter) also registers a `PageableHandlerMethodArgumentResolver` as well as an instance of `SortHandlerMethodArgumentResolver`.
The registration enables `Pageable` and `Sort` as valid controller method arguments, as the following example shows:

Example 50. Using Pageable as a controller method argument

```
@Controller
@RequestMapping("/users")
class UserController {

  private final UserRepository repository;

  UserController(UserRepository repository) {
    this.repository = repository;
  }

  @RequestMapping
  String showUsers(Model model, Pageable pageable) {

    model.addAttribute("users", repository.findAll(pageable));
    return "users";
  }
}
```

The preceding method signature causes Spring MVC try to derive a `Pageable` instance from the request parameters by using the following default configuration:

|`page`|                                                                                                                             Page you want to retrieve. 0-indexed and defaults to 0.                                                                                                                              |
|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|`size`|                                                                                                                              Size of the page you want to retrieve. Defaults to 20.                                                                                                                              |
|`sort`|Properties that should be sorted by in the format `property,property(,ASC|DESC)(,IgnoreCase)`. The default sort direction is case-sensitive ascending. Use multiple `sort` parameters if you want to switch direction or case sensitivity — for example, `?sort=firstname&sort=lastname,asc&sort=city,ignorecase`.|

To customize this behavior, register a bean that implements the `PageableHandlerMethodArgumentResolverCustomizer` interface or the `SortHandlerMethodArgumentResolverCustomizer` interface, respectively.
Its `customize()` method gets called, letting you change settings, as the following example shows:

```
@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    return s -> s.setPropertyDelimiter("<-->");
}
```

If setting the properties of an existing `MethodArgumentResolver` is not sufficient for your purpose, extend either `SpringDataWebConfiguration` or the HATEOAS-enabled equivalent, override the `pageableResolver()` or `sortResolver()` methods, and import your customized configuration file instead of using the `@Enable` annotation.

If you need multiple `Pageable` or `Sort` instances to be resolved from the request (for multiple tables, for example), you can use Spring’s `@Qualifier` annotation to distinguish one from another.
The request parameters then have to be prefixed with `${qualifier}_`.
The following example shows the resulting method signature:

```
String showUsers(Model model,
      @Qualifier("thing1") Pageable first,
      @Qualifier("thing2") Pageable second) { … }
```

You have to populate `thing1_page`, `thing2_page`, and so on.

The default `Pageable` passed into the method is equivalent to a `PageRequest.of(0, 20)`, but you can customize it by using the `@PageableDefault` annotation on the `Pageable` parameter.

Miykael_xxm's avatar
Miykael_xxm 已提交
1767
##### Hypermedia Support for Pageables
M
Mao 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824

Spring HATEOAS ships with a representation model class (`PagedResources`) that allows enriching the content of a `Page` instance with the necessary `Page` metadata as well as links to let the clients easily navigate the pages.
The conversion of a `Page` to a `PagedResources` is done by an implementation of the Spring HATEOAS `ResourceAssembler` interface, called the `PagedResourcesAssembler`.
The following example shows how to use a `PagedResourcesAssembler` as a controller method argument:

Example 51. Using a PagedResourcesAssembler as controller method argument

```
@Controller
class PersonController {

  @Autowired PersonRepository repository;

  @RequestMapping(value = "/persons", method = RequestMethod.GET)
  HttpEntity<PagedResources<Person>> persons(Pageable pageable,
    PagedResourcesAssembler assembler) {

    Page<Person> persons = repository.findAll(pageable);
    return new ResponseEntity<>(assembler.toResources(persons), HttpStatus.OK);
  }
}
```

Enabling the configuration, as shown in the preceding example, lets the `PagedResourcesAssembler` be used as a controller method argument.
Calling `toResources(…)` on it has the following effects:

* The content of the `Page` becomes the content of the `PagedResources` instance.

* The `PagedResources` object gets a `PageMetadata` instance attached, and it is populated with information from the `Page` and the underlying `PageRequest`.

* The `PagedResources` may get `prev` and `next` links attached, depending on the page’s state.
  The links point to the URI to which the method maps.
  The pagination parameters added to the method match the setup of the `PageableHandlerMethodArgumentResolver` to make sure the links can be resolved later.

Assume we have 30 `Person` instances in the database.
You can now trigger a request (`GET [http://localhost:8080/persons](http://localhost:8080/persons)`) and see output similar to the following:

```
{ "links" : [ { "rel" : "next",
                "href" : "http://localhost:8080/persons?page=1&size=20" }
  ],
  "content" : [
     … // 20 Person instances rendered here
  ],
  "pageMetadata" : {
    "size" : 20,
    "totalElements" : 30,
    "totalPages" : 2,
    "number" : 0
  }
}
```

The assembler produced the correct URI and also picked up the default configuration to resolve the parameters into a `Pageable` for an upcoming request.
This means that, if you change that configuration, the links automatically adhere to the change.
By default, the assembler points to the controller method it was invoked in, but you can customize that by passing a custom `Link` to be used as base to build the pagination links, which overloads the `PagedResourcesAssembler.toResource(…)` method.

Miykael_xxm's avatar
Miykael_xxm 已提交
1825
##### Spring Data Jackson Modules
M
Mao 已提交
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844

The core module, and some of the store specific ones, ship with a set of Jackson Modules for types, like `org.springframework.data.geo.Distance` and `org.springframework.data.geo.Point`, used by the Spring Data domain.  
Those Modules are imported once [web support](#core.web) is enabled and `com.fasterxml.jackson.databind.ObjectMapper` is available.

During initialization `SpringDataJacksonModules`, like the `SpringDataJacksonConfiguration`, get picked up by the infrastructure, so that the declared `com.fasterxml.jackson.databind.Module`s are made available to the Jackson `ObjectMapper`.

Data binding mixins for the following domain types are registered by the common infrastructure.

```
org.springframework.data.geo.Distance
org.springframework.data.geo.Point
org.springframework.data.geo.Box
org.springframework.data.geo.Circle
org.springframework.data.geo.Polygon
```

|   |The individual module may provide additional `SpringDataJacksonModules`.  <br/>Please refer to the store specific section for more details.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
1845
##### Web Databinding Support
M
Mao 已提交
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

You can use Spring Data projections (described in [Projections](#projections)) to bind incoming request payloads by using either [JSONPath](https://goessner.net/articles/JsonPath/) expressions (requires [Jayway JsonPath](https://github.com/json-path/JsonPath) or [XPath](https://www.w3.org/TR/xpath-31/) expressions (requires [XmlBeam](https://xmlbeam.org/)), as the following example shows:

Example 52. HTTP payload binding using JSONPath or XPath expressions

```
@ProjectedPayload
public interface UserPayload {

  @XBRead("//firstname")
  @JsonPath("$..firstname")
  String getFirstname();

  @XBRead("/lastname")
  @JsonPath({ "$.lastname", "$.user.lastname" })
  String getLastname();
}
```

You can use the type shown in the preceding example as a Spring MVC handler method argument or by using `ParameterizedTypeReference` on one of methods of the `RestTemplate`.
The preceding method declarations would try to find `firstname` anywhere in the given document.
The `lastname` XML lookup is performed on the top-level of the incoming document.
The JSON variant of that tries a top-level `lastname` first but also tries `lastname` nested in a `user` sub-document if the former does not return a value.
That way, changes in the structure of the source document can be mitigated easily without having clients calling the exposed methods (usually a drawback of class-based payload binding).

Nested projections are supported as described in [Projections](#projections).
If the method returns a complex, non-interface type, a Jackson `ObjectMapper` is used to map the final value.

For Spring MVC, the necessary converters are registered automatically as soon as `@EnableSpringDataWebSupport` is active and the required dependencies are available on the classpath.
For usage with `RestTemplate`, register a `ProjectingJackson2HttpMessageConverter` (JSON) or `XmlBeamHttpMessageConverter` manually.

For more information, see the [web projection example](https://github.com/spring-projects/spring-data-examples/tree/master/web/projection) in the canonical [Spring Data Examples repository](https://github.com/spring-projects/spring-data-examples).

Miykael_xxm's avatar
Miykael_xxm 已提交
1879
##### Querydsl Web Support
M
Mao 已提交
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960

For those stores that have [QueryDSL](http://www.querydsl.com/) integration, you can derive queries from the attributes contained in a `Request` query string.

Consider the following query string:

```
?firstname=Dave&lastname=Matthews
```

Given the `User` object from the previous examples, you can resolve a query string to the following value by using the `QuerydslPredicateArgumentResolver`, as follows:

```
QUser.user.firstname.eq("Dave").and(QUser.user.lastname.eq("Matthews"))
```

|   |The feature is automatically enabled, along with `@EnableSpringDataWebSupport`, when Querydsl is found on the classpath.|
|---|------------------------------------------------------------------------------------------------------------------------|

Adding a `@QuerydslPredicate` to the method signature provides a ready-to-use `Predicate`, which you can run by using the `QuerydslPredicateExecutor`.

|   |Type information is typically resolved from the method’s return type.<br/>Since that information does not necessarily match the domain type, it might be a good idea to use the `root` attribute of `QuerydslPredicate`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The following example shows how to use `@QuerydslPredicate` in a method signature:

```
@Controller
class UserController {

  @Autowired UserRepository repository;

  @RequestMapping(value = "/", method = RequestMethod.GET)
  String index(Model model, @QuerydslPredicate(root = User.class) Predicate predicate,    (1)
          Pageable pageable, @RequestParam MultiValueMap<String, String> parameters) {

    model.addAttribute("users", repository.findAll(predicate, pageable));

    return "index";
  }
}
```

|**1**|Resolve query string arguments to matching `Predicate` for `User`.|
|-----|------------------------------------------------------------------|

The default binding is as follows:

* `Object` on simple properties as `eq`.

* `Object` on collection like properties as `contains`.

* `Collection` on simple properties as `in`.

You can customize those bindings through the `bindings` attribute of `@QuerydslPredicate` or by making use of Java 8 `default methods` and adding the `QuerydslBinderCustomizer` method to the repository interface, as follows:

```
interface UserRepository extends CrudRepository<User, String>,
                                 QuerydslPredicateExecutor<User>,                (1)
                                 QuerydslBinderCustomizer<QUser> {               (2)

  @Override
  default void customize(QuerydslBindings bindings, QUser user) {

    bindings.bind(user.username).first((path, value) -> path.contains(value))    (3)
    bindings.bind(String.class)
      .first((StringPath path, String value) -> path.containsIgnoreCase(value)); (4)
    bindings.excluding(user.password);                                           (5)
  }
}
```

|**1**|                         `QuerydslPredicateExecutor` provides access to specific finder methods for `Predicate`.                          |
|-----|------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|`QuerydslBinderCustomizer` defined on the repository interface is automatically picked up and shortcuts `@QuerydslPredicate(bindings=…​)`.|
|**3**|                            Define the binding for the `username` property to be a simple `contains` binding.                             |
|**4**|                      Define the default binding for `String` properties to be a case-insensitive `contains` match.                       |
|**5**|                                       Exclude the `password` property from `Predicate` resolution.                                       |

|   |You can register a `QuerydslBinderCustomizerDefaults` bean holding default Querydsl bindings before applying specific bindings from the repository or `@QuerydslPredicate`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
1961
#### 4.8.3. Repository Populators
M
Mao 已提交
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031

If you work with the Spring JDBC module, you are probably familiar with the support for populating a `DataSource` with SQL scripts.
A similar abstraction is available on the repositories level, although it does not use SQL as the data definition language because it must be store-independent.
Thus, the populators support XML (through Spring’s OXM abstraction) and JSON (through Jackson) to define data with which to populate the repositories.

Assume you have a file called `data.json` with the following content:

Example 53. Data defined in JSON

```
[ { "_class" : "com.acme.Person",
 "firstname" : "Dave",
  "lastname" : "Matthews" },
  { "_class" : "com.acme.Person",
 "firstname" : "Carter",
  "lastname" : "Beauford" } ]
```

You can populate your repositories by using the populator elements of the repository namespace provided in Spring Data Commons.
To populate the preceding data to your `PersonRepository`, declare a populator similar to the following:

Example 54. Declaring a Jackson repository populator

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:repository="http://www.springframework.org/schema/data/repository"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    https://www.springframework.org/schema/data/repository/spring-repository.xsd">

  <repository:jackson2-populator locations="classpath:data.json" />

</beans>
```

The preceding declaration causes the `data.json` file to be read and deserialized by a Jackson `ObjectMapper`.

The type to which the JSON object is unmarshalled is determined by inspecting the `_class` attribute of the JSON document.
The infrastructure eventually selects the appropriate repository to handle the object that was deserialized.

To instead use XML to define the data the repositories should be populated with, you can use the `unmarshaller-populator` element.
You configure it to use one of the XML marshaller options available in Spring OXM. See the [Spring reference documentation](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/data-access.html#oxm) for details.
The following example shows how to unmarshall a repository populator with JAXB:

Example 55. Declaring an unmarshalling repository populator (using JAXB)

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:repository="http://www.springframework.org/schema/data/repository"
  xmlns:oxm="http://www.springframework.org/schema/oxm"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    https://www.springframework.org/schema/data/repository/spring-repository.xsd
    http://www.springframework.org/schema/oxm
    https://www.springframework.org/schema/oxm/spring-oxm.xsd">

  <repository:unmarshaller-populator locations="classpath:data.json"
    unmarshaller-ref="unmarshaller" />

  <oxm:jaxb2-marshaller contextPath="com.acme" />

</beans>
```

Miykael_xxm's avatar
Miykael_xxm 已提交
2032
## 5. Projections
M
Mao 已提交
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062

Spring Data query methods usually return one or multiple instances of the aggregate root managed by the repository.
However, it might sometimes be desirable to create projections based on certain attributes of those types.
Spring Data allows modeling dedicated return types, to more selectively retrieve partial views of the managed aggregates.

Imagine a repository and aggregate root type such as the following example:

Example 56. A sample aggregate and repository

```
class Person {

  @Id UUID id;
  String firstname, lastname;
  Address address;

  static class Address {
    String zipCode, city, street;
  }
}

interface PersonRepository extends Repository<Person, UUID> {

  Collection<Person> findByLastname(String lastname);
}
```

Now imagine that we want to retrieve the person’s name attributes only.
What means does Spring Data offer to achieve this? The rest of this chapter answers that question.

Miykael_xxm's avatar
Miykael_xxm 已提交
2063
### 5.1. Interface-based Projections
M
Mao 已提交
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112

The easiest way to limit the result of the queries to only the name attributes is by declaring an interface that exposes accessor methods for the properties to be read, as shown in the following example:

Example 57. A projection interface to retrieve a subset of attributes

```
interface NamesOnly {

  String getFirstname();
  String getLastname();
}
```

The important bit here is that the properties defined here exactly match properties in the aggregate root.
Doing so lets a query method be added as follows:

Example 58. A repository using an interface based projection with a query method

```
interface PersonRepository extends Repository<Person, UUID> {

  Collection<NamesOnly> findByLastname(String lastname);
}
```

The query execution engine creates proxy instances of that interface at runtime for each element returned and forwards calls to the exposed methods to the target object.

|   |Declaring a method in your `Repository` that overrides a base method (e.g. declared in `CrudRepository`, a store-specific repository interface, or the `Simple…Repository`) results in a call to the base method regardless of the declared return type. Make sure to use a compatible return type as base methods cannot be used for projections. Some store modules support `@Query` annotations to turn an overridden base method into a query method that then can be used to return projections.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Projections can be used recursively. If you want to include some of the `Address` information as well, create a projection interface for that and return that interface from the declaration of `getAddress()`, as shown in the following example:

Example 59. A projection interface to retrieve a subset of attributes

```
interface PersonSummary {

  String getFirstname();
  String getLastname();
  AddressSummary getAddress();

  interface AddressSummary {
    String getCity();
  }
}
```

On method invocation, the `address` property of the target instance is obtained and wrapped into a projecting proxy in turn.

Miykael_xxm's avatar
Miykael_xxm 已提交
2113
#### 5.1.1. Closed Projections
M
Mao 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129

A projection interface whose accessor methods all match properties of the target aggregate is considered to be a closed projection. The following example (which we used earlier in this chapter, too) is a closed projection:

Example 60. A closed projection

```
interface NamesOnly {

  String getFirstname();
  String getLastname();
}
```

If you use a closed projection, Spring Data can optimize the query execution, because we know about all the attributes that are needed to back the projection proxy.
For more details on that, see the module-specific part of the reference documentation.

Miykael_xxm's avatar
Miykael_xxm 已提交
2130
#### 5.1.2. Open Projections
M
Mao 已提交
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203

Accessor methods in projection interfaces can also be used to compute new values by using the `@Value` annotation, as shown in the following example:

Example 61. An Open Projection

```
interface NamesOnly {

  @Value("#{target.firstname + ' ' + target.lastname}")
  String getFullName();

}
```

The aggregate root backing the projection is available in the `target` variable.
A projection interface using `@Value` is an open projection.
Spring Data cannot apply query execution optimizations in this case, because the SpEL expression could use any attribute of the aggregate root.

The expressions used in `@Value` should not be too complex — you want to avoid programming in `String` variables.
For very simple expressions, one option might be to resort to default methods (introduced in Java 8), as shown in the following example:

Example 62. A projection interface using a default method for custom logic

```
interface NamesOnly {

  String getFirstname();
  String getLastname();

  default String getFullName() {
    return getFirstname().concat(" ").concat(getLastname());
  }
}
```

This approach requires you to be able to implement logic purely based on the other accessor methods exposed on the projection interface.
A second, more flexible, option is to implement the custom logic in a Spring bean and then invoke that from the SpEL expression, as shown in the following example:

Example 63. Sample Person object

```
@Component
class MyBean {

  String getFullName(Person person) {

  }
}

interface NamesOnly {

  @Value("#{@myBean.getFullName(target)}")
  String getFullName();

}
```

Notice how the SpEL expression refers to `myBean` and invokes the `getFullName(…)` method and forwards the projection target as a method parameter.
Methods backed by SpEL expression evaluation can also use method parameters, which can then be referred to from the expression.
The method parameters are available through an `Object` array named `args`. The following example shows how to get a method parameter from the `args` array:

Example 64. Sample Person object

```
interface NamesOnly {

  @Value("#{args[0] + ' ' + target.firstname + '!'}")
  String getSalutation(String prefix);
}
```

Again, for more complex expressions, you should use a Spring bean and let the expression invoke a method, as described [earlier](#projections.interfaces.open.bean-reference).

Miykael_xxm's avatar
Miykael_xxm 已提交
2204
#### 5.1.3. Nullable Wrappers
M
Mao 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227

Getters in projection interfaces can make use of nullable wrappers for improved null-safety. Currently supported wrapper types are:

* `java.util.Optional`

* `com.google.common.base.Optional`

* `scala.Option`

* `io.vavr.control.Option`

Example 65. A projection interface using nullable wrappers

```
interface NamesOnly {

  Optional<String> getFirstname();
}
```

If the underlying projection value is not `null`, then values are returned using the present-representation of the wrapper type.
In case the backing value is `null`, then the getter method returns the empty representation of the used wrapper type.

Miykael_xxm's avatar
Miykael_xxm 已提交
2228
### 5.2. Class-based Projections (DTOs)
M
Mao 已提交
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264

Another way of defining projections is by using value type DTOs (Data Transfer Objects) that hold properties for the fields that are supposed to be retrieved.
These DTO types can be used in exactly the same way projection interfaces are used, except that no proxying happens and no nested projections can be applied.

If the store optimizes the query execution by limiting the fields to be loaded, the fields to be loaded are determined from the parameter names of the constructor that is exposed.

The following example shows a projecting DTO:

Example 66. A projecting DTO

```
class NamesOnly {

  private final String firstname, lastname;

  NamesOnly(String firstname, String lastname) {

    this.firstname = firstname;
    this.lastname = lastname;
  }

  String getFirstname() {
    return this.firstname;
  }

  String getLastname() {
    return this.lastname;
  }

  // equals(…) and hashCode() implementations
}
```

|   |Avoid boilerplate code for projection DTOs<br/><br/>You can dramatically simplify the code for a DTO by using [Project Lombok](https://projectlombok.org), which provides an `@Value` annotation (not to be confused with Spring’s `@Value` annotation shown in the earlier interface examples).<br/>If you use Project Lombok’s `@Value` annotation, the sample DTO shown earlier would become the following:<br/><br/>```<br/>@Value<br/>class NamesOnly {<br/>	String firstname, lastname;<br/>}<br/>```<br/><br/>Fields are `private final` by default, and the class exposes a constructor that takes all fields and automatically gets `equals(…)` and `hashCode()` methods implemented.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
2265
### 5.3. Dynamic Projections
M
Mao 已提交
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297

So far, we have used the projection type as the return type or element type of a collection.
However, you might want to select the type to be used at invocation time (which makes it dynamic).
To apply dynamic projections, use a query method such as the one shown in the following example:

Example 67. A repository using a dynamic projection parameter

```
interface PersonRepository extends Repository<Person, UUID> {

  <T> Collection<T> findByLastname(String lastname, Class<T> type);
}
```

This way, the method can be used to obtain the aggregates as is or with a projection applied, as shown in the following example:

Example 68. Using a repository with dynamic projections

```
void someMethod(PersonRepository people) {

  Collection<Person> aggregates =
    people.findByLastname("Matthews", Person.class);

  Collection<NamesOnly> aggregates =
    people.findByLastname("Matthews", NamesOnly.class);
}
```

|   |Query parameters of type `Class` are inspected whether they qualify as dynamic projection parameter.<br/>If the actual return type of the query equals the generic parameter type of the `Class` parameter, then the matching `Class` parameter is not available for usage within the query or SpEL expressions.<br/>If you want to use a `Class` parameter as query argument then make sure to use a different generic parameter, for example `Class<?>`.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
2298
## 6. Query by Example
M
Mao 已提交
2299

Miykael_xxm's avatar
Miykael_xxm 已提交
2300
### 6.1. Introduction
M
Mao 已提交
2301 2302 2303 2304 2305 2306 2307

This chapter provides an introduction to Query by Example and explains how to use it.

Query by Example (QBE) is a user-friendly querying technique with a simple interface.
It allows dynamic query creation and does not require you to write queries that contain field names.
In fact, Query by Example does not require you to write queries by using store-specific query languages at all.

Miykael_xxm's avatar
Miykael_xxm 已提交
2308
### 6.2. Usage
M
Mao 已提交
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392

The Query by Example API consists of three parts:

* Probe: The actual example of a domain object with populated fields.

* `ExampleMatcher`: The `ExampleMatcher` carries details on how to match particular fields.
  It can be reused across multiple Examples.

* `Example`: An `Example` consists of the probe and the `ExampleMatcher`.
  It is used to create the query.

Query by Example is well suited for several use cases:

* Querying your data store with a set of static or dynamic constraints.

* Frequent refactoring of the domain objects without worrying about breaking existing queries.

* Working independently from the underlying data store API.

Query by Example also has several limitations:

* No support for nested or grouped property constraints, such as `firstname = ?0 or (firstname = ?1 and lastname = ?2)`.

* Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.

Before getting started with Query by Example, you need to have a domain object.
To get started, create an interface for your repository, as shown in the following example:

Example 69. Sample Person object

```
public class Person {

  @Id
  private String id;
  private String firstname;
  private String lastname;
  private Address address;

  // … getters and setters omitted
}
```

The preceding example shows a simple domain object.
You can use it to create an `Example`.
By default, fields having `null` values are ignored, and strings are matched by using the store specific defaults.

|   |Inclusion of properties into a Query by Example criteria is based on nullability. Properties using primitive types (`int`, `double`, …) are always included unless [ignoring the property path](#query-by-example.matchers).|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Examples can be built by either using the `of` factory method or by using [`ExampleMatcher`](#query-by-example.matchers). `Example` is immutable.
The following listing shows a simple Example:

Example 70. Simple Example

```
Person person = new Person();                         (1)
person.setFirstname("Dave");                          (2)

Example<Person> example = Example.of(person);         (3)
```

|**1**|Create a new instance of the domain object.|
|-----|-------------------------------------------|
|**2**|       Set the properties to query.        |
|**3**|           Create the `Example`.           |

You can run the example queries by using repositories.
To do so, let your repository interface extend `QueryByExampleExecutor<T>`.
The following listing shows an excerpt from the `QueryByExampleExecutor` interface:

Example 71. The `QueryByExampleExecutor`

```
public interface QueryByExampleExecutor<T> {

  <S extends T> S findOne(Example<S> example);

  <S extends T> Iterable<S> findAll(Example<S> example);

  // … more functionality omitted.
}
```

Miykael_xxm's avatar
Miykael_xxm 已提交
2393
### 6.3. Example Matchers
M
Mao 已提交
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463

Examples are not limited to default settings.
You can specify your own defaults for string matching, null handling, and property-specific settings by using the `ExampleMatcher`, as shown in the following example:

Example 72. Example matcher with customized matching

```
Person person = new Person();                          (1)
person.setFirstname("Dave");                           (2)

ExampleMatcher matcher = ExampleMatcher.matching()     (3)
  .withIgnorePaths("lastname")                         (4)
  .withIncludeNullValues()                             (5)
  .withStringMatcher(StringMatcher.ENDING);            (6)

Example<Person> example = Example.of(person, matcher); (7)
```

|**1**|                                              Create a new instance of the domain object.                                              |
|-----|---------------------------------------------------------------------------------------------------------------------------------------|
|**2**|                                                            Set properties.                                                            |
|**3**|     Create an `ExampleMatcher` to expect all values to match.<br/>It is usable at this stage even without further configuration.      |
|**4**|                               Construct a new `ExampleMatcher` to ignore the `lastname` property path.                                |
|**5**|                  Construct a new `ExampleMatcher` to ignore the `lastname` property path and to include null values.                  |
|**6**|Construct a new `ExampleMatcher` to ignore the `lastname` property path, to include null values, and to perform suffix string matching.|
|**7**|                        Create a new `Example` based on the domain object and the configured `ExampleMatcher`.                         |

By default, the `ExampleMatcher` expects all values set on the probe to match.
If you want to get results matching any of the predicates defined implicitly, use `ExampleMatcher.matchingAny()`.

You can specify behavior for individual properties (such as "firstname" and "lastname" or, for nested properties, "address.city").
You can tune it with matching options and case sensitivity, as shown in the following example:

Example 73. Configuring matcher options

```
ExampleMatcher matcher = ExampleMatcher.matching()
  .withMatcher("firstname", endsWith())
  .withMatcher("lastname", startsWith().ignoreCase());
}
```

Another way to configure matcher options is to use lambdas (introduced in Java 8).
This approach creates a callback that asks the implementor to modify the matcher.
You need not return the matcher, because configuration options are held within the matcher instance.
The following example shows a matcher that uses lambdas:

Example 74. Configuring matcher options with lambdas

```
ExampleMatcher matcher = ExampleMatcher.matching()
  .withMatcher("firstname", match -> match.endsWith())
  .withMatcher("firstname", match -> match.startsWith());
}
```

Queries created by `Example` use a merged view of the configuration.
Default matching settings can be set at the `ExampleMatcher` level, while individual settings can be applied to particular property paths.
Settings that are set on `ExampleMatcher` are inherited by property path settings unless they are defined explicitly.
Settings on a property patch have higher precedence than default settings.
The following table describes the scope of the various `ExampleMatcher` settings:

|      Setting       |              Scope               |
|--------------------|----------------------------------|
|   Null-handling    |         `ExampleMatcher`         |
|  String matching   |`ExampleMatcher` and property path|
|Ignoring properties |          Property path           |
|  Case sensitivity  |`ExampleMatcher` and property path|
|Value transformation|          Property path           |

Miykael_xxm's avatar
Miykael_xxm 已提交
2464
## 7. Auditing
M
Mao 已提交
2465

Miykael_xxm's avatar
Miykael_xxm 已提交
2466
### 7.1. Basics
M
Mao 已提交
2467 2468 2469 2470 2471 2472 2473 2474

Spring Data provides sophisticated support to transparently keep track of who created or changed an entity and when the change happened. To benefit from that functionality, you have to equip your entity classes with auditing metadata that can be defined either using annotations or by implementing an interface.
Additionally, auditing has to be enabled either through Annotation configuration or XML configuration to register the required infrastructure components.
Please refer to the store-specific section for configuration samples.

|   |Applications that only track creation and modification dates do not need to specify an [`AuditorAware`](#auditing.auditor-aware).|
|---|---------------------------------------------------------------------------------------------------------------------------------|

Miykael_xxm's avatar
Miykael_xxm 已提交
2475
#### 7.1.1. Annotation-based Auditing Metadata
M
Mao 已提交
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518

We provide `@CreatedBy` and `@LastModifiedBy` to capture the user who created or modified the entity as well as `@CreatedDate` and `@LastModifiedDate` to capture when the change happened.

Example 75. An audited entity

```
class Customer {

  @CreatedBy
  private User user;

  @CreatedDate
  private Instant createdDate;

  // … further properties omitted
}
```

As you can see, the annotations can be applied selectively, depending on which information you want to capture. The annotations capturing when changes were made can be used on properties of type Joda-Time, `DateTime`, legacy Java `Date` and `Calendar`, JDK8 date and time types, and `long` or `Long`.

Auditing metadata does not necessarily need to live in the root level entity but can be added to an embedded one (depending on the actual store in use), as shown in the snipped below.

Example 76. Audit metadata in embedded entity

```
class Customer {

  private AuditMetadata auditingMetadata;

  // … further properties omitted
}

class AuditMetadata {

  @CreatedBy
  private User user;

  @CreatedDate
  private Instant createdDate;

}
```

Miykael_xxm's avatar
Miykael_xxm 已提交
2519
#### 7.1.2. Interface-based Auditing Metadata
M
Mao 已提交
2520 2521 2522

In case you do not want to use annotations to define auditing metadata, you can let your domain class implement the `Auditable` interface. It exposes setter methods for all of the auditing properties.

Miykael_xxm's avatar
Miykael_xxm 已提交
2523
#### 7.1.3. `AuditorAware`
M
Mao 已提交
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547

In case you use either `@CreatedBy` or `@LastModifiedBy`, the auditing infrastructure somehow needs to become aware of the current principal. To do so, we provide an `AuditorAware<T>` SPI interface that you have to implement to tell the infrastructure who the current user or system interacting with the application is. The generic type `T` defines what type the properties annotated with `@CreatedBy` or `@LastModifiedBy` have to be.

The following example shows an implementation of the interface that uses Spring Security’s `Authentication` object:

Example 77. Implementation of `AuditorAware` based on Spring Security

```
class SpringSecurityAuditorAware implements AuditorAware<User> {

  @Override
  public Optional<User> getCurrentAuditor() {

    return Optional.ofNullable(SecurityContextHolder.getContext())
            .map(SecurityContext::getAuthentication)
            .filter(Authentication::isAuthenticated)
            .map(Authentication::getPrincipal)
            .map(User.class::cast);
  }
}
```

The implementation accesses the `Authentication` object provided by Spring Security and looks up the custom `UserDetails` instance that you have created in your `UserDetailsService` implementation. We assume here that you are exposing the domain user through the `UserDetails` implementation but that, based on the `Authentication` found, you could also look it up from anywhere.

Miykael_xxm's avatar
Miykael_xxm 已提交
2548
#### 7.1.4. `ReactiveAuditorAware`
M
Mao 已提交
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573

When using reactive infrastructure you might want to make use of contextual information to provide `@CreatedBy` or `@LastModifiedBy` information.
We provide an `ReactiveAuditorAware<T>` SPI interface that you have to implement to tell the infrastructure who the current user or system interacting with the application is. The generic type `T` defines what type the properties annotated with `@CreatedBy` or `@LastModifiedBy` have to be.

The following example shows an implementation of the interface that uses reactive Spring Security’s `Authentication` object:

Example 78. Implementation of `ReactiveAuditorAware` based on Spring Security

```
class SpringSecurityAuditorAware implements ReactiveAuditorAware<User> {

  @Override
  public Mono<User> getCurrentAuditor() {

    return ReactiveSecurityContextHolder.getContext()
                .map(SecurityContext::getAuthentication)
                .filter(Authentication::isAuthenticated)
                .map(Authentication::getPrincipal)
                .map(User.class::cast);
  }
}
```

The implementation accesses the `Authentication` object provided by Spring Security and looks up the custom `UserDetails` instance that you have created in your `UserDetailsService` implementation. We assume here that you are exposing the domain user through the `UserDetails` implementation but that, based on the `Authentication` found, you could also look it up from anywhere.

Miykael_xxm's avatar
Miykael_xxm 已提交
2574
## Appendices
M
Mao 已提交
2575

Miykael_xxm's avatar
Miykael_xxm 已提交
2576
## Appendix A: Namespace reference
M
Mao 已提交
2577

Miykael_xxm's avatar
Miykael_xxm 已提交
2578
### The `<repositories />` Element
M
Mao 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589

The `<repositories />` element triggers the setup of the Spring Data repository infrastructure. The most important attribute is `base-package`, which defines the package to scan for Spring Data repository interfaces. See “[XML Configuration](#repositories.create-instances.spring)”. The following table describes the attributes of the `<repositories />` element:

|             Name             |                                                                                                                              Description                                                                                                                               |
|------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|        `base-package`        |Defines the package to be scanned for repository interfaces that extend `*Repository` (the actual interface is determined by the specific Spring Data module) in auto-detection mode. All packages below the configured package are scanned, too. Wildcards are allowed.|
|  `repository-impl-postfix`   |                                               Defines the postfix to autodetect custom repository implementations. Classes whose names end with the configured postfix are considered as candidates. Defaults to `Impl`.                                               |
|   `query-lookup-strategy`    |                                   Determines the strategy to be used to create finder queries. See “[Query Lookup Strategies](#repositories.query-methods.query-lookup-strategies)” for details. Defaults to `create-if-not-found`.                                    |
|   `named-queries-location`   |                                                                                      Defines the location to search for a Properties file containing externally defined queries.                                                                                       |
|`consider-nested-repositories`|                                                                                       Whether nested repository interface definitions should be considered. Defaults to `false`.                                                                                       |

Miykael_xxm's avatar
Miykael_xxm 已提交
2590
## Appendix B: Populators namespace reference
M
Mao 已提交
2591

Miykael_xxm's avatar
Miykael_xxm 已提交
2592
### The \<populator /\> element
M
Mao 已提交
2593 2594 2595 2596 2597 2598 2599

The `<populator />` element allows to populate the a data store via the Spring Data repository infrastructure.<sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>

|   Name    |                                      Description                                       |
|-----------|----------------------------------------------------------------------------------------|
|`locations`|Where to find the files to read the objects from the repository shall be populated with.|

Miykael_xxm's avatar
Miykael_xxm 已提交
2600
## Appendix C: Repository query keywords
M
Mao 已提交
2601

Miykael_xxm's avatar
Miykael_xxm 已提交
2602
### Supported query method subject keywords
M
Mao 已提交
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615

The following table lists the subject keywords generally supported by the Spring Data repository query derivation mechanism to express the predicate.
Consult the store-specific documentation for the exact list of supported keywords, because some keywords listed here might not be supported in a particular store.

|                              Keyword                               |                                                                                                                                         Description                                                                                                                                         |
|--------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|`find…By`, `read…By`, `get…By`, `query…By`, `search…By`, `stream…By`|General query method returning typically the repository type, a `Collection` or `Streamable` subtype or a result wrapper such as `Page`, `GeoResults` or any other store-specific result wrapper. Can be used as `findBy…`, `findMyDomainTypeBy…` or in combination with additional keywords.|
|                            `exists…By`                             |                                                                                                                 Exists projection, returning typically a `boolean` result.                                                                                                                  |
|                             `count…By`                             |                                                                                                                        Count projection returning a numeric result.                                                                                                                         |
|                      `delete…By`, `remove…By`                      |                                                                                                        Delete query method returning either no result (`void`) or the delete count.                                                                                                         |
|                 `…First<number>…`, `…Top<number>…`                 |                                                              Limit the query results to the first `<number>` of results. This keyword can occur in any place of the subject between `find` (and the other keywords) and `by`.                                                               |
|                            `…Distinct…`                            |                            Use a distinct query to return only unique results. Consult the store-specific documentation whether that feature is supported. This keyword can occur in any place of the subject between `find` (and the other keywords) and `by`.                             |

Miykael_xxm's avatar
Miykael_xxm 已提交
2616
### Supported query method predicate keywords and modifiers
M
Mao 已提交
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659

The following table lists the predicate keywords generally supported by the Spring Data repository query derivation mechanism.
However, consult the store-specific documentation for the exact list of supported keywords, because some keywords listed here might not be supported in a particular store.

|   Logical keyword   |             Keyword expressions              |
|---------------------|----------------------------------------------|
|        `AND`        |                    `And`                     |
|        `OR`         |                     `Or`                     |
|       `AFTER`       |              `After`, `IsAfter`              |
|      `BEFORE`       |             `Before`, `IsBefore`             |
|    `CONTAINING`     |   `Containing`, `IsContaining`, `Contains`   |
|      `BETWEEN`      |            `Between`, `IsBetween`            |
|    `ENDING_WITH`    |   `EndingWith`, `IsEndingWith`, `EndsWith`   |
|      `EXISTS`       |                   `Exists`                   |
|       `FALSE`       |              `False`, `IsFalse`              |
|   `GREATER_THAN`    |        `GreaterThan`, `IsGreaterThan`        |
|`GREATER_THAN_EQUALS`|   `GreaterThanEqual`, `IsGreaterThanEqual`   |
|        `IN`         |                 `In`, `IsIn`                 |
|        `IS`         |       `Is`, `Equals`, (or no keyword)        |
|     `IS_EMPTY`      |              `IsEmpty`, `Empty`              |
|   `IS_NOT_EMPTY`    |           `IsNotEmpty`, `NotEmpty`           |
|    `IS_NOT_NULL`    |            `NotNull`, `IsNotNull`            |
|      `IS_NULL`      |               `Null`, `IsNull`               |
|     `LESS_THAN`     |           `LessThan`, `IsLessThan`           |
|  `LESS_THAN_EQUAL`  |      `LessThanEqual`, `IsLessThanEqual`      |
|       `LIKE`        |               `Like`, `IsLike`               |
|       `NEAR`        |               `Near`, `IsNear`               |
|        `NOT`        |                `Not`, `IsNot`                |
|      `NOT_IN`       |              `NotIn`, `IsNotIn`              |
|     `NOT_LIKE`      |            `NotLike`, `IsNotLike`            |
|       `REGEX`       |      `Regex`, `MatchesRegex`, `Matches`      |
|   `STARTING_WITH`   |`StartingWith`, `IsStartingWith`, `StartsWith`|
|       `TRUE`        |               `True`, `IsTrue`               |
|      `WITHIN`       |             `Within`, `IsWithin`             |

In addition to filter predicates, the following list of modifiers is supported:

|             Keyword              |                                                     Description                                                     |
|----------------------------------|---------------------------------------------------------------------------------------------------------------------|
|   `IgnoreCase`, `IgnoringCase`   |                           Used with a predicate keyword for case-insensitive comparison.                            |
|`AllIgnoreCase`, `AllIgnoringCase`|               Ignore case for all suitable properties. Used somewhere in the query method predicate.                |
|            `OrderBy…`            |Specify a static sorting order followed by the property path and direction (e. g. `OrderByFirstnameAscLastnameDesc`).|

Miykael_xxm's avatar
Miykael_xxm 已提交
2660
## Appendix D: Repository query return types
M
Mao 已提交
2661

Miykael_xxm's avatar
Miykael_xxm 已提交
2662
### Supported Query Return Types
M
Mao 已提交
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702

The following table lists the return types generally supported by Spring Data repositories.
However, consult the store-specific documentation for the exact list of supported return types, because some types listed here might not be supported in a particular store.

|   |Geospatial types (such as `GeoResult`, `GeoResults`, and `GeoPage`) are available only for data stores that support geospatial queries.<br/>Some store modules may define their own result wrapper types.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|                                          Return type                                           |                                                                                                                              Description                                                                                                                              |
|------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|                                             `void`                                             |                                                                                                                       Denotes no return value.                                                                                                                        |
|                                           Primitives                                           |                                                                                                                           Java primitives.                                                                                                                            |
|                                         Wrapper types                                          |                                                                                                                          Java wrapper types.                                                                                                                          |
|                                              `T`                                               |                                     A unique entity. Expects the query method to return one result at most. If no result is found, `null` is returned. More than one result triggers an `IncorrectResultSizeDataAccessException`.                                     |
|                                         `Iterator<T>`                                          |                                                                                                                            An `Iterator`.                                                                                                                             |
|                                        `Collection<T>`                                         |                                                                                                                            A `Collection`.                                                                                                                            |
|                                           `List<T>`                                            |                                                                                                                               A `List`.                                                                                                                               |
|                                         `Optional<T>`                                          |             A Java 8 or Guava `Optional`. Expects the query method to return one result at most. If no result is found, `Optional.empty()` or `Optional.absent()` is returned. More than one result triggers an `IncorrectResultSizeDataAccessException`.             |
|                                          `Option<T>`                                           |                                                                            Either a Scala or Vavr `Option` type. Semantically the same behavior as Java 8’s `Optional`, described earlier.                                                                            |
|                                          `Stream<T>`                                           |                                                                                                                          A Java 8 `Stream`.                                                                                                                           |
|                                        `Streamable<T>`                                         |                                                                      A convenience extension of `Iterable` that directy exposes methods to stream, map and filter results, concatenate them etc.                                                                      |
|Types that implement `Streamable` and take a `Streamable` constructor or factory method argument|                Types that expose a constructor or `….of(…)`/`….valueOf(…)` factory method taking a `Streamable` as argument. See [Returning Custom Streamable Wrapper Types](#repositories.collections-and-iterables.streamable-wrapper) for details.                 |
|                                Vavr `Seq`, `List`, `Map`, `Set`                                |                                                                         Vavr collection types. See [Support for Vavr Collections](#repositories.collections-and-iterables.vavr) for details.                                                                          |
|                                          `Future<T>`                                           |                                                               A `Future`. Expects a method to be annotated with `@Async` and requires Spring’s asynchronous method execution capability to be enabled.                                                                |
|                                     `CompletableFuture<T>`                                     |                                                      A Java 8 `CompletableFuture`. Expects a method to be annotated with `@Async` and requires Spring’s asynchronous method execution capability to be enabled.                                                       |
|                                       `ListenableFuture`                                       |                                        A `org.springframework.util.concurrent.ListenableFuture`. Expects a method to be annotated with `@Async` and requires Spring’s asynchronous method execution capability to be enabled.                                         |
|                                           `Slice<T>`                                           |                                                                       A sized chunk of data with an indication of whether there is more data available. Requires a `Pageable` method parameter.                                                                       |
|                                           `Page<T>`                                            |                                                                          A `Slice` with additional information, such as the total number of results. Requires a `Pageable` method parameter.                                                                          |
|                                         `GeoResult<T>`                                         |                                                                                       A result entry with additional information, such as the distance to a reference location.                                                                                       |
|                                        `GeoResults<T>`                                         |                                                                              A list of `GeoResult<T>` with additional information, such as the average distance to a reference location.                                                                              |
|                                          `GeoPage<T>`                                          |                                                                                          A `Page` with `GeoResult<T>`, such as the average distance to a reference location.                                                                                          |
|                                           `Mono<T>`                                            |A Project Reactor `Mono` emitting zero or one element using reactive repositories. Expects the query method to return one result at most. If no result is found, `Mono.empty()` is returned. More than one result triggers an `IncorrectResultSizeDataAccessException`.|
|                                           `Flux<T>`                                            |                                                   A Project Reactor `Flux` emitting zero, one, or many elements using reactive repositories. Queries returning `Flux` can emit also an infinite number of elements.                                                   |
|                                          `Single<T>`                                           |     A RxJava `Single` emitting a single element using reactive repositories. Expects the query method to return one result at most. If no result is found, `Mono.empty()` is returned. More than one result triggers an `IncorrectResultSizeDataAccessException`.     |
|                                           `Maybe<T>`                                           |    A RxJava `Maybe` emitting zero or one element using reactive repositories. Expects the query method to return one result at most. If no result is found, `Mono.empty()` is returned. More than one result triggers an `IncorrectResultSizeDataAccessException`.    |
|                                         `Flowable<T>`                                          |                                                   A RxJava `Flowable` emitting zero, one, or many elements using reactive repositories. Queries returning `Flowable` can emit also an infinite number of elements.                                                    |

---

[1](#_footnoteref_1). see [XML Configuration](#repositories.create-instances.spring)