86.b68daf67.js 198.4 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1
(window.webpackJsonp=window.webpackJsonp||[]).push([[86],{519:function(e,t,a){"use strict";a.r(t);var o=a(56),r=Object(o.a)({},(function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[a("h1",{attrs:{id:"preface"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#preface"}},[e._v("#")]),e._v(" Preface")]),e._v(" "),a("p",[e._v("The Spring Data Commons project applies core Spring concepts to the development of solutions using many relational and non-relational data stores.")]),e._v(" "),a("h2",{attrs:{id:"_1-project-metadata"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-project-metadata"}},[e._v("#")]),e._v(" 1. Project Metadata")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Version control: "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-data-commons",target:"_blank",rel:"noopener noreferrer"}},[e._v("https://github.com/spring-projects/spring-data-commons"),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[e._v("Bugtracker: "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-data-commons/issues",target:"_blank",rel:"noopener noreferrer"}},[e._v("https://github.com/spring-projects/spring-data-commons/issues"),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[e._v("Release repository: "),a("a",{attrs:{href:"https://repo.spring.io/libs-release",target:"_blank",rel:"noopener noreferrer"}},[e._v("https://repo.spring.io/libs-release"),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[e._v("Milestone repository: "),a("a",{attrs:{href:"https://repo.spring.io/libs-milestone",target:"_blank",rel:"noopener noreferrer"}},[e._v("https://repo.spring.io/libs-milestone"),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[e._v("Snapshot repository: "),a("a",{attrs:{href:"https://repo.spring.io/libs-snapshot",target:"_blank",rel:"noopener noreferrer"}},[e._v("https://repo.spring.io/libs-snapshot"),a("OutboundLink")],1)])])]),e._v(" "),a("h2",{attrs:{id:"reference-documentation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#reference-documentation"}},[e._v("#")]),e._v(" Reference Documentation")]),e._v(" "),a("h2",{attrs:{id:"_2-dependencies"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-dependencies"}},[e._v("#")]),e._v(" 2. Dependencies")]),e._v(" "),a("p",[e._v("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 "),a("code",[e._v("<dependencyManagement />")]),e._v(" section of your POM as follows:")]),e._v(" "),a("p",[e._v("Example 1. Using the Spring Data release train BOM")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("<dependencyManagement>\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.data</groupId>\n      <artifactId>spring-data-bom</artifactId>\n      <version>2021.1.2</version>\n      <scope>import</scope>\n      <type>pom</type>\n    </dependency>\n  </dependencies>\n</dependencyManagement>\n")])])]),a("p",[e._v("The current release train version is "),a("code",[e._v("2021.1.2")]),e._v(". The train version uses "),a("a",{attrs:{href:"https://calver.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("calver"),a("OutboundLink")],1),e._v(" with the pattern "),a("code",[e._v("YYYY.MINOR.MICRO")]),e._v(".\nThe version name follows "),a("code",[e._v("${calver}")]),e._v(" for GA releases and service releases and the following pattern for all other versions: "),a("code",[e._v("${calver}-${modifier}")]),e._v(", where "),a("code",[e._v("modifier")]),e._v(" can be one of the following:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("SNAPSHOT")]),e._v(": Current snapshots")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("M1")]),e._v(", "),a("code",[e._v("M2")]),e._v(", and so on: Milestones")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("RC1")]),e._v(", "),a("code",[e._v("RC2")]),e._v(", and so on: Release candidates")])])]),e._v(" "),a("p",[e._v("You can find a working example of using the BOMs in our "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-data-examples/tree/master/bom",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Data examples repository"),a("OutboundLink")],1),e._v(". With that in place, you can declare the Spring Data modules you would like to use without a version in the "),a("code",[e._v("<dependencies />")]),e._v(" block, as follows:")]),e._v(" "),a("p",[e._v("Example 2. Declaring a dependency to a Spring Data module")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("<dependencies>\n  <dependency>\n    <groupId>org.springframework.data</groupId>\n    <artifactId>spring-data-jpa</artifactId>\n  </dependency>\n<dependencies>\n")])])]),a("h3",{attrs:{id:"_2-1-dependency-management-with-spring-boot"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-dependency-management-with-spring-boot"}},[e._v("#")]),e._v(" 2.1. Dependency Management with Spring Boot")]),e._v(" "),a("p",[e._v("Spring Boot selects a recent version of Spring Data modules for you. If you still want to upgrade to a newer version, set\nthe "),a("code",[e._v("spring-data-releasetrain.version")]),e._v(" property to the "),a("a",{attrs:{href:"#dependencies.train-version"}},[e._v("train version and iteration")]),e._v(" you would like to use.")]),e._v(" "),a("h3",{attrs:{id:"_2-2-spring-framework"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-spring-framework"}},[e._v("#")]),e._v(" 2.2. Spring Framework")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("h2",{attrs:{id:"_3-object-mapping-fundamentals"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-object-mapping-fundamentals"}},[e._v("#")]),e._v(" 3. Object Mapping Fundamentals")]),e._v(" "),a("p",[e._v("This section covers the fundamentals of Spring Data object mapping, object creation, field and property access, mutability and immutability.\nNote, that this section only applies to Spring Data modules that do not use the object mapping of the underlying data store (like JPA).\nAlso be sure to consult the store-specific sections for store-specific object mapping, like indexes, customizing column or field names or the like.")]),e._v(" "),a("p",[e._v("Core responsibility of the Spring Data object mapping is to create instances of domain objects and map the store-native data structures onto those.\nThis means we need two fundamental steps:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("Instance creation by using one of the constructors exposed.")])]),e._v(" "),a("li",[a("p",[e._v("Instance population to materialize all exposed properties.")])])]),e._v(" "),a("h3",{attrs:{id:"_3-1-object-creation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-1-object-creation"}},[e._v("#")]),e._v(" 3.1. Object creation")]),e._v(" "),a("p",[e._v("Spring Data automatically tries to detect a persistent entity’s constructor to be used to materialize objects of that type.\nThe resolution algorithm works as follows:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("If there is a single constructor, it is used.")])]),e._v(" "),a("li",[a("p",[e._v("If there are multiple constructors and exactly one is annotated with "),a("code",[e._v("@PersistenceConstructor")]),e._v(", it is used.")])]),e._v(" "),a("li",[a("p",[e._v("If there’s a no-argument constructor, it is used.\nOther constructors will be ignored.")])])]),e._v(" "),a("p",[e._v("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.).\nThis also requires either parameter names information available in the class file or an "),a("code",[e._v("@ConstructorProperties")]),e._v(" annotation being present on the constructor.")]),e._v(" "),a("p",[e._v("The value resolution can be customized by using Spring Framework’s "),a("code",[e._v("@Value")]),e._v(" value annotation using a store-specific SpEL expression.\nPlease consult the section on store specific mappings for further details.")]),e._v(" "),a("p",[e._v("Object creation internals")]),e._v(" "),a("p",[e._v("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.\nI.e. for this example type:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class Person {\n  Person(String firstname, String lastname) { … }\n}\n")])])]),a("p",[e._v("we will create a factory class semantically equivalent to this one at runtime:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class PersonObjectInstantiator implements ObjectInstantiator {\n\n  Object newInstance(Object... args) {\n    return new Person((String) args[0], (String) args[1]);\n  }\n}\n")])])]),a("p",[e._v("This gives us a roundabout 10% performance boost over reflection.\nFor the domain class to be eligible for such optimization, it needs to adhere to a set of constraints:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("it must not be a private class")])]),e._v(" "),a("li",[a("p",[e._v("it must not be a non-static inner class")])]),e._v(" "),a("li",[a("p",[e._v("it must not be a CGLib proxy class")])]),e._v(" "),a("li",[a("p",[e._v("the constructor to be used by Spring Data must not be private")])])]),e._v(" "),a("p",[e._v("If any of these criteria match, Spring Data will fall back to entity instantiation via reflection.")]),e._v(" "),a("h3",{attrs:{id:"_3-2-property-population"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-property-population"}},[e._v("#")]),e._v(" 3.2. Property population")]),e._v(" "),a("p",[e._v("Once an instance of the entity has been created, Spring Data populates all remaining persistent properties of that class.\nUnless 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.\nAfter that, all non-transient properties that have not already been populated by the constructor are set on the entity instance.\nFor that we use the following algorithm:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("If the property is immutable but exposes a "),a("code",[e._v("with…")]),e._v(" method (see below), we use the "),a("code",[e._v("with…")]),e._v(" method to create a new entity instance with the new property value.")])]),e._v(" "),a("li",[a("p",[e._v("If property access (i.e. access through getters and setters) is defined, we’re invoking the setter method.")])]),e._v(" "),a("li",[a("p",[e._v("If the property is mutable we set the field directly.")])]),e._v(" "),a("li",[a("p",[e._v("If the property is immutable we’re using the constructor to be used by persistence operations (see "),a("a",{attrs:{href:"#mapping.object-creation"}},[e._v("Object creation")]),e._v(") to create a copy of the instance.")])]),e._v(" "),a("li",[a("p",[e._v("By default, we set the field value directly.")])])]),e._v(" "),a("p",[e._v("Property population internals")]),e._v(" "),a("p",[e._v("Similarly to our "),a("a",{attrs:{href:"#mapping.object-creation.details"}},[e._v("optimizations in object construction")]),e._v(" we also use Spring Data runtime generated accessor classes to interact with the entity instance.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class Person {\n\n  private final Long id;\n  private String firstname;\n  private @AccessType(Type.PROPERTY) String lastname;\n\n  Person() {\n    this.id = null;\n  }\n\n  Person(Long id, String firstname, String lastname) {\n    // Field assignments\n  }\n\n  Person withId(Long id) {\n    return new Person(id, this.firstname, this.lastame);\n  }\n\n  void setLastname(String lastname) {\n    this.lastname = lastname;\n  }\n}\n")])])]),a("p",[e._v("Example 3. A generated Property Accessor")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('class PersonPropertyAccessor implements PersistentPropertyAccessor {\n\n  private static final MethodHandle firstname;              (2)\n\n  private Person person;                                    (1)\n\n  public void setProperty(PersistentProperty property, Object value) {\n\n    String name = property.getName();\n\n    if ("firstname".equals(name)) {\n      firstname.invoke(person, (String) value);             (2)\n    } else if ("id".equals(name)) {\n      this.person = person.withId((Long) value);            (3)\n    } else if ("lastname".equals(name)) {\n      this.person.setLastname((String) value);              (4)\n    }\n  }\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("PropertyAccessor’s hold a mutable instance of the underlying object. This is, to enable mutations of otherwise immutable properties.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("By default, Spring Data uses field-access to read and write property values. As per visibility rules of "),a("code",[e._v("private")]),e._v(" fields, "),a("code",[e._v("MethodHandles")]),e._v(" are used to interact with fields.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("The class exposes a "),a("code",[e._v("withId(…)")]),e._v(" 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 "),a("code",[e._v("withId(…)")]),e._v(" creates a new "),a("code",[e._v("Person")]),e._v(" object. All subsequent mutations will take place in the new instance leaving the previous untouched.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Using property-access allows direct method invocations without using "),a("code",[e._v("MethodHandles")]),e._v(".")])])])]),e._v(" "),a("p",[e._v("This gives us a roundabout 25% performance boost over reflection.\nFor the domain class to be eligible for such optimization, it needs to adhere to a set of constraints:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Types must not reside in the default or under the "),a("code",[e._v("java")]),e._v(" package.")])]),e._v(" "),a("li",[a("p",[e._v("Types and their constructors must be "),a("code",[e._v("public")])])]),e._v(" "),a("li",[a("p",[e._v("Types that are inner classes must be "),a("code",[e._v("static")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("The used Java Runtime must allow for declaring classes in the originating "),a("code",[e._v("ClassLoader")]),e._v(". Java 9 and newer impose certain limitations.")])])]),e._v(" "),a("p",[e._v("By default, Spring Data attempts to use generated property accessors and falls back to reflection-based ones if a limitation is detected.")]),e._v(" "),a("p",[e._v("Let’s have a look at the following entity:")]),e._v(" "),a("p",[e._v("Example 4. A sample entity")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class Person {\n\n  private final @Id Long id;                                                (1)\n  private final String firstname, lastname;                                 (2)\n  private final LocalDate birthday;\n  private final int age;                                                    (3)\n\n  private String comment;                                                   (4)\n  private @AccessType(Type.PROPERTY) String remarks;                        (5)\n\n  static Person of(String firstname, String lastname, LocalDate birthday) { (6)\n\n    return new Person(null, firstname, lastname, birthday,\n      Period.between(birthday, LocalDate.now()).getYears());\n  }\n\n  Person(Long id, String firstname, String lastname, LocalDate birthday, int age) { (6)\n\n    this.id = id;\n    this.firstname = firstname;\n    this.lastname = lastname;\n    this.birthday = birthday;\n    this.age = age;\n  }\n\n  Person withId(Long id) {                                                  (1)\n    return new Person(id, this.firstname, this.lastname, this.birthday, this.age);\n  }\n\n  void setRemarks(String remarks) {                                         (5)\n    this.remarks = remarks;\n  }\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("The identifier property is final but set to "),a("code",[e._v("null")]),e._v(" in the constructor."),a("br"),e._v("The class exposes a "),a("code",[e._v("withId(…)")]),e._v(" method that’s used to set the identifier, e.g. when an instance is inserted into the datastore and an identifier has been generated."),a("br"),e._v("The original "),a("code",[e._v("Person")]),e._v(" instance stays unchanged as a new one is created."),a("br"),e._v("The same pattern is usually applied for other properties that are store managed but might have to be changed for persistence operations."),a("br"),e._v("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.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("The "),a("code",[e._v("firstname")]),e._v(" and "),a("code",[e._v("lastname")]),e._v(" properties are ordinary immutable properties potentially exposed through getters.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("The "),a("code",[e._v("age")]),e._v(" property is an immutable but derived one from the "),a("code",[e._v("birthday")]),e._v(" property."),a("br"),e._v("With the design shown, the database value will trump the defaulting as Spring Data uses the only declared constructor."),a("br"),e._v("Even if the intent is that the calculation should be preferred, it’s important that this constructor also takes "),a("code",[e._v("age")]),e._v(" 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 "),a("code",[e._v("with…")]),e._v(" method being present.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("The "),a("code",[e._v("comment")]),e._v(" property is mutable is populated by setting its field directly.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("5")])]),e._v(" "),a("td",[e._v("The "),a("code",[e._v("remarks")]),e._v(" properties are mutable and populated by setting the "),a("code",[e._v("comment")]),e._v(" field directly or by invoking the setter method for")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("6")])]),e._v(" "),a("td",[e._v("The class exposes a factory method and a constructor for object creation."),a("br"),e._v("The core idea here is to use factory methods instead of additional constructors to avoid the need for constructor disambiguation through "),a("code",[e._v("@PersistenceConstructor")]),e._v("."),a("br"),e._v("Instead, defaulting of properties is handled within the factory method.")])])])]),e._v(" "),a("h3",{attrs:{id:"_3-3-general-recommendations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-3-general-recommendations"}},[e._v("#")]),e._v(" 3.3. General recommendations")]),e._v(" "),a("ul",[a("li",[a("p",[a("em",[e._v("Try to stick to immutable objects")]),e._v(" — Immutable objects are straightforward to create as materializing an object is then a matter of calling its constructor only.\nAlso, this avoids your domain objects to be littered with setter methods that allow client code to manipulate the objects state.\nIf you need those, prefer to make them package protected so that they can only be invoked by a limited amount of co-located types.\nConstructor-only materialization is up to 30% faster than properties population.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Provide an all-args constructor")]),e._v(" — 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.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Use factory methods instead of overloaded constructors to avoid "),a("code",[e._v("@PersistenceConstructor")])]),e._v(" — 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.\nIt’s an established pattern to rather use static factory methods to expose these variants of the all-args constructor.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Make sure you adhere to the constraints that allow the generated instantiator and property accessor classes to be used")]),e._v(" —")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("For identifiers to be generated, still use a final field in combination with an all-arguments persistence constructor (preferred) or a "),a("code",[e._v("with…")]),e._v(" method")]),e._v(" —")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Use Lombok to avoid boilerplate code")]),e._v(" — 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 "),a("code",[e._v("@AllArgsConstructor")]),e._v(".")])])]),e._v(" "),a("h4",{attrs:{id:"_3-3-1-overriding-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-3-1-overriding-properties"}},[e._v("#")]),e._v(" 3.3.1. Overriding Properties")]),e._v(" "),a("p",[e._v("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.\nConsider the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public class SuperType {\n\n   private CharSequence field;\n\n   public SuperType(CharSequence field) {\n      this.field = field;\n   }\n\n   public CharSequence getField() {\n      return this.field;\n   }\n\n   public void setField(CharSequence field) {\n      this.field = field;\n   }\n}\n\npublic class SubType extends SuperType {\n\n   private String field;\n\n   public SubType(String field) {\n      super(field);\n      this.field = field;\n   }\n\n   @Override\n   public String getField() {\n      return this.field;\n   }\n\n   public void setField(String field) {\n      this.field = field;\n\n      // optional\n      super.setField(field);\n   }\n}\n")])])]),a("p",[e._v("Both classes define a "),a("code",[e._v("field")]),e._v(" using assignable types. "),a("code",[e._v("SubType")]),e._v(" however shadows "),a("code",[e._v("SuperType.field")]),e._v(".\nDepending on the class design, using the constructor could be the only default approach to set "),a("code",[e._v("SuperType.field")]),e._v(".\nAlternatively, calling "),a("code",[e._v("super.setField(…)")]),e._v(" in the setter could set the "),a("code",[e._v("field")]),e._v(" in "),a("code",[e._v("SuperType")]),e._v(".\nAll these mechanisms create conflicts to some degree because the properties share the same name yet might represent two distinct values.\nSpring Data skips super-type properties if types are not assignable.\nThat 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.\nWe generally recommend using distinct property names.")]),e._v(" "),a("p",[e._v("Spring Data modules generally support overridden properties holding different values.\nFrom a programming model perspective there are a few things to consider:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("Which property should be persisted (default to all declared properties)?\nYou can exclude properties by annotating these with "),a("code",[e._v("@Transient")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("How to represent properties in your data store?\nUsing 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.")])]),e._v(" "),a("li",[a("p",[e._v("Using "),a("code",[e._v("@AccessType(PROPERTY)")]),e._v(" cannot be used as the super-property cannot be generally set without making any further assumptions of the setter implementation.")])])]),e._v(" "),a("h3",{attrs:{id:"_3-4-kotlin-support"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-kotlin-support"}},[e._v("#")]),e._v(" 3.4. Kotlin support")]),e._v(" "),a("p",[e._v("Spring Data adapts specifics of Kotlin to allow object creation and mutation.")]),e._v(" "),a("h4",{attrs:{id:"_3-4-1-kotlin-object-creation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-1-kotlin-object-creation"}},[e._v("#")]),e._v(" 3.4.1. Kotlin object creation")]),e._v(" "),a("p",[e._v("Kotlin classes are supported to be instantiated , all classes are immutable by default and require explicit property declarations to define mutable properties.\nConsider the following "),a("code",[e._v("data")]),e._v(" class "),a("code",[e._v("Person")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("data class Person(val id: String, val name: String)\n")])])]),a("p",[e._v("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 "),a("code",[e._v("@PersistenceConstructor")]),e._v(" to indicate a constructor preference:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('data class Person(var id: String, val name: String) {\n\n    @PersistenceConstructor\n    constructor(id: String) : this(id, "unknown")\n}\n')])])]),a("p",[e._v("Kotlin supports parameter optionality by allowing default values to be used if a parameter is not provided.\nWhen 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 "),a("code",[e._v("null")]),e._v(") so Kotlin can apply parameter defaulting.Consider the following class that applies parameter defaulting for "),a("code",[e._v("name")])]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('data class Person(var id: String, val name: String = "unknown")\n')])])]),a("p",[e._v("Every time the "),a("code",[e._v("name")]),e._v(" parameter is either not part of the result or its value is "),a("code",[e._v("null")]),e._v(", then the "),a("code",[e._v("name")]),e._v(" defaults to "),a("code",[e._v("unknown")]),e._v(".")]),e._v(" "),a("h4",{attrs:{id:"_3-4-2-property-population-of-kotlin-data-classes"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-2-property-population-of-kotlin-data-classes"}},[e._v("#")]),e._v(" 3.4.2. Property population of Kotlin data classes")]),e._v(" "),a("p",[e._v("In Kotlin, all classes are immutable by default and require explicit property declarations to define mutable properties.\nConsider the following "),a("code",[e._v("data")]),e._v(" class "),a("code",[e._v("Person")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("data class Person(val id: String, val name: String)\n")])])]),a("p",[e._v("This class is effectively immutable.\nIt allows creating new instances as Kotlin generates a "),a("code",[e._v("copy(…)")]),e._v(" method that creates new object instances copying all property values from the existing object and applying property values provided as arguments to the method.")]),e._v(" "),a("h4",{attrs:{id:"_3-4-3-kotlin-overriding-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-3-kotlin-overriding-properties"}},[e._v("#")]),e._v(" 3.4.3. Kotlin Overriding Properties")]),e._v(" "),a("p",[e._v("Kotlin allows declaring "),a("a",{attrs:{href:"https://kotlinlang.org/docs/inheritance.html#overriding-properties",target:"_blank",rel:"noopener noreferrer"}},[e._v("property overrides"),a("OutboundLink")],1),e._v(" to alter properties in subclasses.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("open class SuperType(open var field: Int)\n\nclass SubType(override var field: Int = 1) :\n\tSuperType(field) {\n}\n")])])]),a("p",[e._v("Such an arrangement renders two properties with the name "),a("code",[e._v("field")]),e._v(".\nKotlin generates property accessors (getters and setters) for each property in each class.\nEffectively, the code looks like as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public class SuperType {\n\n   private int field;\n\n   public SuperType(int field) {\n      this.field = field;\n   }\n\n   public int getField() {\n      return this.field;\n   }\n\n   public void setField(int field) {\n      this.field = field;\n   }\n}\n\npublic final class SubType extends SuperType {\n\n   private int field;\n\n   public SubType(int field) {\n      super(field);\n      this.field = field;\n   }\n\n   public int getField() {\n      return this.field;\n   }\n\n   public void setField(int field) {\n      this.field = field;\n   }\n}\n")])])]),a("p",[e._v("Getters and setters on "),a("code",[e._v("SubType")]),e._v(" set only "),a("code",[e._v("SubType.field")]),e._v(" and not "),a("code",[e._v("SuperType.field")]),e._v(".\nIn such an arrangement, using the constructor is the only default approach to set "),a("code",[e._v("SuperType.field")]),e._v(".\nAdding a method to "),a("code",[e._v("SubType")]),e._v(" to set "),a("code",[e._v("SuperType.field")]),e._v(" via "),a("code",[e._v("this.SuperType.field = …")]),e._v(" is possible but falls outside of supported conventions.\nProperty overrides create conflicts to some degree because the properties share the same name yet might represent two distinct values.\nWe generally recommend using distinct property names.")]),e._v(" "),a("p",[e._v("Spring Data modules generally support overridden properties holding different values.\nFrom a programming model perspective there are a few things to consider:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("Which property should be persisted (default to all declared properties)?\nYou can exclude properties by annotating these with "),a("code",[e._v("@Transient")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("How to represent properties in your data store?\nUsing 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.")])]),e._v(" "),a("li",[a("p",[e._v("Using "),a("code",[e._v("@AccessType(PROPERTY)")]),e._v(" cannot be used as the super-property cannot be set.")])])]),e._v(" "),a("h2",{attrs:{id:"_4-working-with-spring-data-repositories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-working-with-spring-data-repositories"}},[e._v("#")]),e._v(" 4. Working with Spring Data Repositories")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[a("em",[e._v("Spring Data repository documentation and your module")]),a("br"),a("br"),e._v("This chapter explains the core concepts and interfaces of Spring Data repositories."),a("br"),e._v("The information in this chapter is pulled from the Spring Data Commons module."),a("br"),e._v("It uses the configuration and code samples for the Java Persistence API (JPA) module."),a("br"),e._v("You should adapt the XML namespace declaration and the types to be extended to the equivalents of the particular module that you use. “"),a("a",{attrs:{href:"#repositories.namespace-reference"}},[e._v("Namespace reference")]),e._v("” covers XML configuration, which is supported across all Spring Data modules that support the repository API. “"),a("a",{attrs:{href:"#repository-query-keywords"}},[e._v("Repository query keywords")]),e._v("” covers the query method keywords supported by the repository abstraction in general."),a("br"),e._v("For detailed information on the specific features of your module, see the chapter on that module of this document.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_4-1-core-concepts"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-1-core-concepts"}},[e._v("#")]),e._v(" 4.1. Core concepts")]),e._v(" "),a("p",[e._v("The central interface in the Spring Data repository abstraction is "),a("code",[e._v("Repository")]),e._v(".\nIt takes the domain class to manage as well as the ID type of the domain class as type arguments.\nThis 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.\nThe "),a("a",{attrs:{href:"https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("CrudRepository")]),a("OutboundLink")],1),e._v(" interface provides sophisticated CRUD functionality for the entity class that is being managed.")]),e._v(" "),a("p",[e._v("Example 5. "),a("code",[e._v("CrudRepository")]),e._v(" Interface")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public interface CrudRepository<T, ID> extends Repository<T, ID> {\n\n  <S extends T> S save(S entity);      (1)\n\n  Optional<T> findById(ID primaryKey); (2)\n\n  Iterable<T> findAll();               (3)\n\n  long count();                        (4)\n\n  void delete(T entity);               (5)\n\n  boolean existsById(ID primaryKey);   (6)\n\n  // … more functionality omitted.\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("Saves the given entity.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("Returns the entity identified by the given ID.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Returns all entities.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Returns the number of entities.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("5")])]),e._v(" "),a("td",[e._v("Deletes the given entity.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("6")])]),e._v(" "),a("td",[e._v("Indicates whether an entity with the given ID exists.")])])])]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("We also provide persistence technology-specific abstractions, such as "),a("code",[e._v("JpaRepository")]),e._v(" or "),a("code",[e._v("MongoRepository")]),e._v("."),a("br"),e._v("Those interfaces extend "),a("code",[e._v("CrudRepository")]),e._v(" and expose the capabilities of the underlying persistence technology in addition to the rather generic persistence technology-agnostic interfaces such as "),a("code",[e._v("CrudRepository")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("On top of the "),a("code",[e._v("CrudRepository")]),e._v(", there is a "),a("a",{attrs:{href:"https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("PagingAndSortingRepository")]),a("OutboundLink")],1),e._v(" abstraction that adds additional methods to ease paginated access to entities:")]),e._v(" "),a("p",[e._v("Example 6. "),a("code",[e._v("PagingAndSortingRepository")]),e._v(" interface")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {\n\n  Iterable<T> findAll(Sort sort);\n\n  Page<T> findAll(Pageable pageable);\n}\n")])])]),a("p",[e._v("To access the second page of "),a("code",[e._v("User")]),e._v(" by a page size of 20, you could do something like the following:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("PagingAndSortingRepository<User, Long> repository = // … get access to a bean\nPage<User> users = repository.findAll(PageRequest.of(1, 20));\n")])])]),a("p",[e._v("In addition to query methods, query derivation for both count and delete queries is available.\nThe following list shows the interface definition for a derived count query:")]),e._v(" "),a("p",[e._v("Example 7. Derived Count Query")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, Long> {\n\n  long countByLastname(String lastname);\n}\n")])])]),a("p",[e._v("The following listing shows the interface definition for a derived delete query:")]),e._v(" "),a("p",[e._v("Example 8. Derived Delete Query")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, Long> {\n\n  long deleteByLastname(String lastname);\n\n  List<User> removeByLastname(String lastname);\n}\n")])])]),a("h3",{attrs:{id:"_4-2-query-methods"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-2-query-methods"}},[e._v("#")]),e._v(" 4.2. Query Methods")]),e._v(" "),a("p",[e._v("Standard CRUD functionality repositories usually have queries on the underlying datastore.\nWith Spring Data, declaring those queries becomes a four-step process:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("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:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonRepository extends Repository<Person, Long> { … }\n")])])])]),e._v(" "),a("li",[a("p",[e._v("Declare query methods on the interface.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonRepository extends Repository<Person, Long> {\n  List<Person> findByLastname(String lastname);\n}\n")])])])]),e._v(" "),a("li",[a("p",[e._v("Set up Spring to create proxy instances for those interfaces, either with "),a("a",{attrs:{href:"#repositories.create-instances.java-config"}},[e._v("JavaConfig")]),e._v(" or with "),a("a",{attrs:{href:"#repositories.create-instances"}},[e._v("XML configuration")]),e._v(".")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("To use Java configuration, create a class similar to the following:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.data.jpa.repository.config.EnableJpaRepositories;\n\n@EnableJpaRepositories\nclass Config { … }\n")])])])]),e._v(" "),a("li",[a("p",[e._v("To use XML configuration, define a bean similar to the following:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<?xml version="1.0" encoding="UTF-8"?>\n<beans xmlns="http://www.springframework.org/schema/beans"\n   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n   xmlns:jpa="http://www.springframework.org/schema/data/jpa"\n   xsi:schemaLocation="http://www.springframework.org/schema/beans\n     https://www.springframework.org/schema/beans/spring-beans.xsd\n     http://www.springframework.org/schema/data/jpa\n     https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">\n\n   <jpa:repositories base-package="com.acme.repositories"/>\n\n</beans>\n')])])]),a("p",[e._v("The JPA namespace is used in this example.\nIf you use the repository abstraction for any other store, you need to change this to the appropriate namespace declaration of your store module.\nIn other words, you should exchange "),a("code",[e._v("jpa")]),e._v(" in favor of, for example, "),a("code",[e._v("mongodb")]),e._v(".")]),e._v(" "),a("p",[e._v("Also, note that the JavaConfig variant does not configure a package explicitly, because the package of the annotated class is used by default.\nTo customize the package to scan, use one of the "),a("code",[e._v("basePackage…")]),e._v(" attributes of the data-store-specific repository’s "),a("code",[e._v("@Enable${store}Repositories")]),e._v("-annotation.")])])])]),e._v(" "),a("li",[a("p",[e._v("Inject the repository instance and use it, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('class SomeClient {\n\n  private final PersonRepository repository;\n\n  SomeClient(PersonRepository repository) {\n    this.repository = repository;\n  }\n\n  void doSomething() {\n    List<Person> persons = repository.findByLastname("Matthews");\n  }\n}\n')])])])])]),e._v(" "),a("p",[e._v("The sections that follow explain each step in detail:")]),e._v(" "),a("ul",[a("li",[a("p",[a("a",{attrs:{href:"#repositories.definition"}},[e._v("Defining Repository Interfaces")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#repositories.query-methods.details"}},[e._v("Defining Query Methods")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#repositories.create-instances"}},[e._v("Creating Repository Instances")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#repositories.custom-implementations"}},[e._v("Custom Implementations for Spring Data Repositories")])])])]),e._v(" "),a("h3",{attrs:{id:"_4-3-defining-repository-interfaces"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-3-defining-repository-interfaces"}},[e._v("#")]),e._v(" 4.3. Defining Repository Interfaces")]),e._v(" "),a("p",[e._v("To define a repository interface, you first need to define a domain class-specific repository interface.\nThe interface must extend "),a("code",[e._v("Repository")]),e._v(" and be typed to the domain class and an ID type.\nIf you want to expose CRUD methods for that domain type, extend "),a("code",[e._v("CrudRepository")]),e._v(" instead of "),a("code",[e._v("Repository")]),e._v(".")]),e._v(" "),a("h4",{attrs:{id:"_4-3-1-fine-tuning-repository-definition"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-3-1-fine-tuning-repository-definition"}},[e._v("#")]),e._v(" 4.3.1. Fine-tuning Repository Definition")]),e._v(" "),a("p",[e._v("Typically, your repository interface extends "),a("code",[e._v("Repository")]),e._v(", "),a("code",[e._v("CrudRepository")]),e._v(", or "),a("code",[e._v("PagingAndSortingRepository")]),e._v(".\nAlternatively, if you do not want to extend Spring Data interfaces, you can also annotate your repository interface with "),a("code",[e._v("@RepositoryDefinition")]),e._v(".\nExtending "),a("code",[e._v("CrudRepository")]),e._v(" exposes a complete set of methods to manipulate your entities.\nIf you prefer to be selective about the methods being exposed, copy the methods you want to expose from "),a("code",[e._v("CrudRepository")]),e._v(" into your domain repository.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Doing so lets you define your own abstractions on top of the provided Spring Data Repositories functionality.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The following example shows how to selectively expose CRUD methods ("),a("code",[e._v("findById")]),e._v(" and "),a("code",[e._v("save")]),e._v(", in this case):")]),e._v(" "),a("p",[e._v("Example 9. Selectively exposing CRUD methods")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@NoRepositoryBean\ninterface MyBaseRepository<T, ID> extends Repository<T, ID> {\n\n  Optional<T> findById(ID id);\n\n  <S extends T> S save(S entity);\n}\n\ninterface UserRepository extends MyBaseRepository<User, Long> {\n  User findByEmailAddress(EmailAddress emailAddress);\n}\n")])])]),a("p",[e._v("In the prior example, you defined a common base interface for all your domain repositories and exposed "),a("code",[e._v("findById(…)")]),e._v(" as well as "),a("code",[e._v("save(…)")]),e._v(".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 "),a("code",[e._v("SimpleJpaRepository")]),e._v("), because they match the method signatures in "),a("code",[e._v("CrudRepository")]),e._v(".\nSo the "),a("code",[e._v("UserRepository")]),e._v(" can now save users, find individual users by ID, and trigger a query to find "),a("code",[e._v("Users")]),e._v(" by email address.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The intermediate repository interface is annotated with "),a("code",[e._v("@NoRepositoryBean")]),e._v("."),a("br"),e._v("Make sure you add that annotation to all repository interfaces for which Spring Data should not create instances at runtime.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_4-3-2-using-repositories-with-multiple-spring-data-modules"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-3-2-using-repositories-with-multiple-spring-data-modules"}},[e._v("#")]),e._v(" 4.3.2. Using Repositories with Multiple Spring Data Modules")]),e._v(" "),a("p",[e._v("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.\nSometimes, applications require using more than one Spring Data module.\nIn such cases, a repository definition must distinguish between persistence technologies.\nWhen it detects multiple repository factories on the class path, Spring Data enters strict repository configuration mode.\nStrict configuration uses details on the repository or the domain class to decide about Spring Data module binding for a repository definition:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("If the repository definition "),a("a",{attrs:{href:"#repositories.multiple-modules.types"}},[e._v("extends the module-specific repository")]),e._v(", it is a valid candidate for the particular Spring Data module.")])]),e._v(" "),a("li",[a("p",[e._v("If the domain class is "),a("a",{attrs:{href:"#repositories.multiple-modules.annotations"}},[e._v("annotated with the module-specific type annotation")]),e._v(", it is a valid candidate for the particular Spring Data module.\nSpring Data modules accept either third-party annotations (such as JPA’s "),a("code",[e._v("@Entity")]),e._v(") or provide their own annotations (such as "),a("code",[e._v("@Document")]),e._v(" for Spring Data MongoDB and Spring Data Elasticsearch).")])])]),e._v(" "),a("p",[e._v("The following example shows a repository that uses module-specific interfaces (JPA in this case):")]),e._v(" "),a("p",[e._v("Example 10. Repository definitions using module-specific interfaces")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface MyRepository extends JpaRepository<User, Long> { }\n\n@NoRepositoryBean\ninterface MyBaseRepository<T, ID> extends JpaRepository<T, ID> { … }\n\ninterface UserRepository extends MyBaseRepository<User, Long> { … }\n")])])]),a("p",[a("code",[e._v("MyRepository")]),e._v(" and "),a("code",[e._v("UserRepository")]),e._v(" extend "),a("code",[e._v("JpaRepository")]),e._v(" in their type hierarchy.\nThey are valid candidates for the Spring Data JPA module.")]),e._v(" "),a("p",[e._v("The following example shows a repository that uses generic interfaces:")]),e._v(" "),a("p",[e._v("Example 11. Repository definitions using generic interfaces")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface AmbiguousRepository extends Repository<User, Long> { … }\n\n@NoRepositoryBean\ninterface MyBaseRepository<T, ID> extends CrudRepository<T, ID> { … }\n\ninterface AmbiguousUserRepository extends MyBaseRepository<User, Long> { … }\n")])])]),a("p",[a("code",[e._v("AmbiguousRepository")]),e._v(" and "),a("code",[e._v("AmbiguousUserRepository")]),e._v(" extend only "),a("code",[e._v("Repository")]),e._v(" and "),a("code",[e._v("CrudRepository")]),e._v(" in their type hierarchy.\nWhile this is fine when using a unique Spring Data module, multiple modules cannot distinguish to which particular Spring Data these repositories should be bound.")]),e._v(" "),a("p",[e._v("The following example shows a repository that uses domain classes with annotations:")]),e._v(" "),a("p",[e._v("Example 12. Repository definitions using domain classes with annotations")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonRepository extends Repository<Person, Long> { … }\n\n@Entity\nclass Person { … }\n\ninterface UserRepository extends Repository<User, Long> { … }\n\n@Document\nclass User { … }\n")])])]),a("p",[a("code",[e._v("PersonRepository")]),e._v(" references "),a("code",[e._v("Person")]),e._v(", which is annotated with the JPA "),a("code",[e._v("@Entity")]),e._v(" annotation, so this repository clearly belongs to Spring Data JPA. "),a("code",[e._v("UserRepository")]),e._v(" references "),a("code",[e._v("User")]),e._v(", which is annotated with Spring Data MongoDB’s "),a("code",[e._v("@Document")]),e._v(" annotation.")]),e._v(" "),a("p",[e._v("The following bad example shows a repository that uses domain classes with mixed annotations:")]),e._v(" "),a("p",[e._v("Example 13. Repository definitions using domain classes with mixed annotations")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface JpaPersonRepository extends Repository<Person, Long> { … }\n\ninterface MongoDBPersonRepository extends Repository<Person, Long> { … }\n\n@Entity\n@Document\nclass Person { … }\n")])])]),a("p",[e._v("This example shows a domain class using both JPA and Spring Data MongoDB annotations.\nIt defines two repositories, "),a("code",[e._v("JpaPersonRepository")]),e._v(" and "),a("code",[e._v("MongoDBPersonRepository")]),e._v(".\nOne is intended for JPA and the other for MongoDB usage.\nSpring Data is no longer able to tell the repositories apart, which leads to undefined behavior.")]),e._v(" "),a("p",[a("a",{attrs:{href:"#repositories.multiple-modules.types"}},[e._v("Repository type details")]),e._v(" and "),a("a",{attrs:{href:"#repositories.multiple-modules.annotations"}},[e._v("distinguishing domain class annotations")]),e._v(" are used for strict repository configuration to identify repository candidates for a particular Spring Data module.\nUsing multiple persistence technology-specific annotations on the same domain type is possible and enables reuse of domain types across multiple persistence technologies.\nHowever, Spring Data can then no longer determine a unique module with which to bind the repository.")]),e._v(" "),a("p",[e._v("The last way to distinguish repositories is by scoping repository base packages.\nBase packages define the starting points for scanning for repository interface definitions, which implies having repository definitions located in the appropriate packages.\nBy default, annotation-driven configuration uses the package of the configuration class.\nThe "),a("a",{attrs:{href:"#repositories.create-instances.spring"}},[e._v("base package in XML-based configuration")]),e._v(" is mandatory.")]),e._v(" "),a("p",[e._v("The following example shows annotation-driven configuration of base packages:")]),e._v(" "),a("p",[e._v("Example 14. Annotation-driven configuration of base packages")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@EnableJpaRepositories(basePackages = "com.acme.repositories.jpa")\n@EnableMongoRepositories(basePackages = "com.acme.repositories.mongo")\nclass Configuration { … }\n')])])]),a("h3",{attrs:{id:"_4-4-defining-query-methods"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-defining-query-methods"}},[e._v("#")]),e._v(" 4.4. Defining Query Methods")]),e._v(" "),a("p",[e._v("The repository proxy has two ways to derive a store-specific query from the method name:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("By deriving the query from the method name directly.")])]),e._v(" "),a("li",[a("p",[e._v("By using a manually defined query.")])])]),e._v(" "),a("p",[e._v("Available options depend on the actual store.\nHowever, there must be a strategy that decides what actual query is created.\nThe next section describes the available options.")]),e._v(" "),a("h4",{attrs:{id:"_4-4-1-query-lookup-strategies"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-1-query-lookup-strategies"}},[e._v("#")]),e._v(" 4.4.1. Query Lookup Strategies")]),e._v(" "),a("p",[e._v("The following strategies are available for the repository infrastructure to resolve the query.\nWith XML configuration, you can configure the strategy at the namespace through the "),a("code",[e._v("query-lookup-strategy")]),e._v(" attribute.\nFor Java configuration, you can use the "),a("code",[e._v("queryLookupStrategy")]),e._v(" attribute of the "),a("code",[e._v("Enable${store}Repositories")]),e._v(" annotation.\nSome strategies may not be supported for particular datastores.")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("CREATE")]),e._v(" attempts to construct a store-specific query from the query method name.\nThe general approach is to remove a given set of well known prefixes from the method name and parse the rest of the method.\nYou can read more about query construction in “"),a("a",{attrs:{href:"#repositories.query-methods.query-creation"}},[e._v("Query Creation")]),e._v("”.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("USE_DECLARED_QUERY")]),e._v(" tries to find a declared query and throws an exception if it cannot find one.\nThe query can be defined by an annotation somewhere or declared by other means.\nSee the documentation of the specific store to find available options for that store.\nIf the repository infrastructure does not find a declared query for the method at bootstrap time, it fails.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("CREATE_IF_NOT_FOUND")]),e._v(" (the default) combines "),a("code",[e._v("CREATE")]),e._v(" and "),a("code",[e._v("USE_DECLARED_QUERY")]),e._v(".\nIt looks up a declared query first, and, if no declared query is found, it creates a custom method name-based query.\nThis is the default lookup strategy and, thus, is used if you do not configure anything explicitly.\nIt allows quick query definition by method names but also custom-tuning of these queries by introducing declared queries as needed.")])])]),e._v(" "),a("h4",{attrs:{id:"_4-4-2-query-creation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-2-query-creation"}},[e._v("#")]),e._v(" 4.4.2. Query Creation")]),e._v(" "),a("p",[e._v("The query builder mechanism built into the Spring Data repository infrastructure is useful for building constraining queries over entities of the repository.")]),e._v(" "),a("p",[e._v("The following example shows how to create a number of queries:")]),e._v(" "),a("p",[e._v("Example 15. Query creation from method names")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonRepository extends Repository<Person, Long> {\n\n  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);\n\n  // Enables the distinct flag for the query\n  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);\n  List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);\n\n  // Enabling ignoring case for an individual property\n  List<Person> findByLastnameIgnoreCase(String lastname);\n  // Enabling ignoring case for all suitable properties\n  List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);\n\n  // Enabling static ORDER BY for a query\n  List<Person> findByLastnameOrderByFirstnameAsc(String lastname);\n  List<Person> findByLastnameOrderByFirstnameDesc(String lastname);\n}\n")])])]),a("p",[e._v("Parsing query method names is divided into subject and predicate.\nThe first part ("),a("code",[e._v("find…By")]),e._v(", "),a("code",[e._v("exists…By")]),e._v(") defines the subject of the query, the second part forms the predicate.\nThe introducing clause (subject) can contain further expressions.\nAny text between "),a("code",[e._v("find")]),e._v(" (or other introducing keywords) and "),a("code",[e._v("By")]),e._v(" is considered to be descriptive unless using one of the result-limiting keywords such as a "),a("code",[e._v("Distinct")]),e._v(" to set a distinct flag on the query to be created or "),a("a",{attrs:{href:"#repositories.limit-query-result"}},[a("code",[e._v("Top")]),e._v("/"),a("code",[e._v("First")]),e._v(" to limit query results")]),e._v(".")]),e._v(" "),a("p",[e._v("The appendix contains the "),a("a",{attrs:{href:"#appendix.query.method.subject"}},[e._v("full list of query method subject keywords")]),e._v(" and "),a("a",{attrs:{href:"#appendix.query.method.predicate"}},[e._v("query method predicate keywords including sorting and letter-casing modifiers")]),e._v(".\nHowever, the first "),a("code",[e._v("By")]),e._v(" acts as a delimiter to indicate the start of the actual criteria predicate.\nAt a very basic level, you can define conditions on entity properties and concatenate them with "),a("code",[e._v("And")]),e._v(" and "),a("code",[e._v("Or")]),e._v(".")]),e._v(" "),a("p",[e._v("The actual result of parsing the method depends on the persistence store for which you create the query.\nHowever, there are some general things to notice:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("The expressions are usually property traversals combined with operators that can be concatenated.\nYou can combine property expressions with "),a("code",[e._v("AND")]),e._v(" and "),a("code",[e._v("OR")]),e._v(".\nYou also get support for operators such as "),a("code",[e._v("Between")]),e._v(", "),a("code",[e._v("LessThan")]),e._v(", "),a("code",[e._v("GreaterThan")]),e._v(", and "),a("code",[e._v("Like")]),e._v(" for the property expressions.\nThe supported operators can vary by datastore, so consult the appropriate part of your reference documentation.")])]),e._v(" "),a("li",[a("p",[e._v("The method parser supports setting an "),a("code",[e._v("IgnoreCase")]),e._v(" flag for individual properties (for example, "),a("code",[e._v("findByLastnameIgnoreCase(…)")]),e._v(") or for all properties of a type that supports ignoring case (usually "),a("code",[e._v("String")]),e._v(" instances — for example, "),a("code",[e._v("findByLastnameAndFirstnameAllIgnoreCase(…)")]),e._v(").\nWhether ignoring cases is supported may vary by store, so consult the relevant sections in the reference documentation for the store-specific query method.")])]),e._v(" "),a("li",[a("p",[e._v("You can apply static ordering by appending an "),a("code",[e._v("OrderBy")]),e._v(" clause to the query method that references a property and by providing a sorting direction ("),a("code",[e._v("Asc")]),e._v(" or "),a("code",[e._v("Desc")]),e._v(").\nTo create a query method that supports dynamic sorting, see “"),a("a",{attrs:{href:"#repositories.special-parameters"}},[e._v("Special parameter handling")]),e._v("”.")])])]),e._v(" "),a("h4",{attrs:{id:"_4-4-3-property-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-3-property-expressions"}},[e._v("#")]),e._v(" 4.4.3. Property Expressions")]),e._v(" "),a("p",[e._v("Property expressions can refer only to a direct property of the managed entity, as shown in the preceding example.\nAt query creation time, you already make sure that the parsed property is a property of the managed domain class.\nHowever, you can also define constraints by traversing nested properties.\nConsider the following method signature:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("List<Person> findByAddressZipCode(ZipCode zipCode);\n")])])]),a("p",[e._v("Assume a "),a("code",[e._v("Person")]),e._v(" has an "),a("code",[e._v("Address")]),e._v(" with a "),a("code",[e._v("ZipCode")]),e._v(".\nIn that case, the method creates the "),a("code",[e._v("x.address.zipCode")]),e._v(" property traversal.\nThe resolution algorithm starts by interpreting the entire part ("),a("code",[e._v("AddressZipCode")]),e._v(") as the property and checks the domain class for a property with that name (uncapitalized).\nIf the algorithm succeeds, it uses that property.\nIf 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, "),a("code",[e._v("AddressZip")]),e._v(" and "),a("code",[e._v("Code")]),e._v(".\nIf 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.\nIf the first split does not match, the algorithm moves the split point to the left ("),a("code",[e._v("Address")]),e._v(", "),a("code",[e._v("ZipCode")]),e._v(") and continues.")]),e._v(" "),a("p",[e._v("Although this should work for most cases, it is possible for the algorithm to select the wrong property.\nSuppose the "),a("code",[e._v("Person")]),e._v(" class has an "),a("code",[e._v("addressZip")]),e._v(" property as well.\nThe algorithm would match in the first split round already, choose the wrong property, and fail (as the type of "),a("code",[e._v("addressZip")]),e._v(" probably has no "),a("code",[e._v("code")]),e._v(" property).")]),e._v(" "),a("p",[e._v("To resolve this ambiguity you can use "),a("code",[e._v("_")]),e._v(" inside your method name to manually define traversal points.\nSo our method name would be as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("List<Person> findByAddress_ZipCode(ZipCode zipCode);\n")])])]),a("p",[e._v("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).")]),e._v(" "),a("h4",{attrs:{id:"_4-4-4-special-parameter-handling"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-4-special-parameter-handling"}},[e._v("#")]),e._v(" 4.4.4. Special parameter handling")]),e._v(" "),a("p",[e._v("To handle parameters in your query, define method parameters as already seen in the preceding examples.\nBesides that, the infrastructure recognizes certain specific types like "),a("code",[e._v("Pageable")]),e._v(" and "),a("code",[e._v("Sort")]),e._v(", to apply pagination and sorting to your queries dynamically.\nThe following example demonstrates these features:")]),e._v(" "),a("p",[e._v("Example 16. Using "),a("code",[e._v("Pageable")]),e._v(", "),a("code",[e._v("Slice")]),e._v(", and "),a("code",[e._v("Sort")]),e._v(" in query methods")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("Page<User> findByLastname(String lastname, Pageable pageable);\n\nSlice<User> findByLastname(String lastname, Pageable pageable);\n\nList<User> findByLastname(String lastname, Sort sort);\n\nList<User> findByLastname(String lastname, Pageable pageable);\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("APIs taking "),a("code",[e._v("Sort")]),e._v(" and "),a("code",[e._v("Pageable")]),e._v(" expect non-"),a("code",[e._v("null")]),e._v(" values to be handed into methods."),a("br"),e._v("If you do not want to apply any sorting or pagination, use "),a("code",[e._v("Sort.unsorted()")]),e._v(" and "),a("code",[e._v("Pageable.unpaged()")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The first method lets you pass an "),a("code",[e._v("org.springframework.data.domain.Pageable")]),e._v(" instance to the query method to dynamically add paging to your statically defined query.\nA "),a("code",[e._v("Page")]),e._v(" knows about the total number of elements and pages available.\nIt does so by the infrastructure triggering a count query to calculate the overall number.\nAs this might be expensive (depending on the store used), you can instead return a "),a("code",[e._v("Slice")]),e._v(".\nA "),a("code",[e._v("Slice")]),e._v(" knows only about whether a next "),a("code",[e._v("Slice")]),e._v(" is available, which might be sufficient when walking through a larger result set.")]),e._v(" "),a("p",[e._v("Sorting options are handled through the "),a("code",[e._v("Pageable")]),e._v(" instance, too.\nIf you need only sorting, add an "),a("code",[e._v("org.springframework.data.domain.Sort")]),e._v(" parameter to your method.\nAs you can see, returning a "),a("code",[e._v("List")]),e._v(" is also possible.\nIn this case, the additional metadata required to build the actual "),a("code",[e._v("Page")]),e._v(" instance is not created (which, in turn, means that the additional count query that would have been necessary is not issued).\nRather, it restricts the query to look up only the given range of entities.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("To find out how many pages you get for an entire query, you have to trigger an additional count query."),a("br"),e._v("By default, this query is derived from the query you actually trigger.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h5",{attrs:{id:"paging-and-sorting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#paging-and-sorting"}},[e._v("#")]),e._v(" Paging and Sorting")]),e._v(" "),a("p",[e._v("You can define simple sorting expressions by using property names.\nYou can concatenate expressions to collect multiple criteria into one expression.")]),e._v(" "),a("p",[e._v("Example 17. Defining sort expressions")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('Sort sort = Sort.by("firstname").ascending()\n  .and(Sort.by("lastname").descending());\n')])])]),a("p",[e._v("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.")]),e._v(" "),a("p",[e._v("Example 18. Defining sort expressions by using the type-safe API")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("TypedSort<Person> person = Sort.sort(Person.class);\n\nSort sort = person.by(Person::getFirstname).ascending()\n  .and(person.by(Person::getLastname).descending());\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[a("code",[e._v("TypedSort.by(…)")]),e._v(" makes use of runtime proxies by (typically) using CGlib, which may interfere with native image compilation when using tools such as Graal VM Native.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("If your store implementation supports Querydsl, you can also use the generated metamodel types to define sort expressions:")]),e._v(" "),a("p",[e._v("Example 19. Defining sort expressions by using the Querydsl API")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("QSort sort = QSort.by(QPerson.firstname.asc())\n  .and(QSort.by(QPerson.lastname.desc()));\n")])])]),a("h4",{attrs:{id:"_4-4-5-limiting-query-results"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-5-limiting-query-results"}},[e._v("#")]),e._v(" 4.4.5. Limiting Query Results")]),e._v(" "),a("p",[e._v("You can limit the results of query methods by using the "),a("code",[e._v("first")]),e._v(" or "),a("code",[e._v("top")]),e._v(" keywords, which you can use interchangeably.\nYou can append an optional numeric value to "),a("code",[e._v("top")]),e._v(" or "),a("code",[e._v("first")]),e._v(" to specify the maximum result size to be returned.\nIf the number is left out, a result size of 1 is assumed.\nThe following example shows how to limit the query size:")]),e._v(" "),a("p",[e._v("Example 20. Limiting the result size of a query with "),a("code",[e._v("Top")]),e._v(" and "),a("code",[e._v("First")])]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("User findFirstByOrderByLastnameAsc();\n\nUser findTopByOrderByAgeDesc();\n\nPage<User> queryFirst10ByLastname(String lastname, Pageable pageable);\n\nSlice<User> findTop3ByLastname(String lastname, Pageable pageable);\n\nList<User> findFirst10ByLastname(String lastname, Sort sort);\n\nList<User> findTop10ByLastname(String lastname, Pageable pageable);\n")])])]),a("p",[e._v("The limiting expressions also support the "),a("code",[e._v("Distinct")]),e._v(" keyword for datastores that support distinct queries.\nAlso, for the queries that limit the result set to one instance, wrapping the result into with the "),a("code",[e._v("Optional")]),e._v(" keyword is supported.")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Limiting the results in combination with dynamic sorting by using a "),a("code",[e._v("Sort")]),e._v(" parameter lets you express query methods for the 'K' smallest as well as for the 'K' biggest elements.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_4-4-6-repository-methods-returning-collections-or-iterables"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-6-repository-methods-returning-collections-or-iterables"}},[e._v("#")]),e._v(" 4.4.6. Repository Methods Returning Collections or Iterables")]),e._v(" "),a("p",[e._v("Query methods that return multiple results can use standard Java "),a("code",[e._v("Iterable")]),e._v(", "),a("code",[e._v("List")]),e._v(", and "),a("code",[e._v("Set")]),e._v(".\nBeyond that, we support returning Spring Data’s "),a("code",[e._v("Streamable")]),e._v(", a custom extension of "),a("code",[e._v("Iterable")]),e._v(", as well as collection types provided by "),a("a",{attrs:{href:"https://www.vavr.io/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Vavr"),a("OutboundLink")],1),e._v(".\nRefer to the appendix explaining all possible "),a("a",{attrs:{href:"#appendix.query.return.types"}},[e._v("query method return types")]),e._v(".")]),e._v(" "),a("h5",{attrs:{id:"using-streamable-as-query-method-return-type"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#using-streamable-as-query-method-return-type"}},[e._v("#")]),e._v(" Using Streamable as Query Method Return Type")]),e._v(" "),a("p",[e._v("You can use "),a("code",[e._v("Streamable")]),e._v(" as alternative to "),a("code",[e._v("Iterable")]),e._v(" or any collection type.\nIt provides convenience methods to access a non-parallel "),a("code",[e._v("Stream")]),e._v(" (missing from "),a("code",[e._v("Iterable")]),e._v(") and the ability to directly "),a("code",[e._v("….filter(…)")]),e._v(" and "),a("code",[e._v("….map(…)")]),e._v(" over the elements and concatenate the "),a("code",[e._v("Streamable")]),e._v(" to others:")]),e._v(" "),a("p",[e._v("Example 21. Using Streamable to combine query method results")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('interface PersonRepository extends Repository<Person, Long> {\n  Streamable<Person> findByFirstnameContaining(String firstname);\n  Streamable<Person> findByLastnameContaining(String lastname);\n}\n\nStreamable<Person> result = repository.findByFirstnameContaining("av")\n  .and(repository.findByLastnameContaining("ea"));\n')])])]),a("h5",{attrs:{id:"returning-custom-streamable-wrapper-types"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#returning-custom-streamable-wrapper-types"}},[e._v("#")]),e._v(" Returning Custom Streamable Wrapper Types")]),e._v(" "),a("p",[e._v("Providing dedicated wrapper types for collections is a commonly used pattern to provide an API for a query result that returns multiple elements.\nUsually, these types are used by invoking a repository method returning a collection-like type and creating an instance of the wrapper type manually.\nYou 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:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("The type implements "),a("code",[e._v("Streamable")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("The type exposes either a constructor or a static factory method named "),a("code",[e._v("of(…)")]),e._v(" or "),a("code",[e._v("valueOf(…)")]),e._v(" that takes "),a("code",[e._v("Streamable")]),e._v(" as an argument.")])])]),e._v(" "),a("p",[e._v("The following listing shows an example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('class Product {                                         (1)\n  MonetaryAmount getPrice() { … }\n}\n\n@RequiredArgsConstructor(staticName = "of")\nclass Products implements Streamable<Product> {         (2)\n\n  private final Streamable<Product> streamable;\n\n  public MonetaryAmount getTotal() {                    (3)\n    return streamable.stream()\n      .map(Priced::getPrice)\n      .reduce(Money.of(0), MonetaryAmount::add);\n  }\n\n  @Override\n  public Iterator<Product> iterator() {                 (4)\n    return streamable.iterator();\n  }\n}\n\ninterface ProductRepository implements Repository<Product, Long> {\n  Products findAllByDescriptionContaining(String text); (5)\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("A "),a("code",[e._v("Product")]),e._v(" entity that exposes API to access the product’s price.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("A wrapper type for a "),a("code",[e._v("Streamable<Product>")]),e._v(" that can be constructed by using "),a("code",[e._v("Products.of(…)")]),e._v(" (factory method created with the Lombok annotation)."),a("br"),e._v("A standard constructor taking the "),a("code",[e._v("Streamable<Product>")]),e._v(" will do as well.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("The wrapper type exposes an additional API, calculating new values on the "),a("code",[e._v("Streamable<Product>")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Implement the "),a("code",[e._v("Streamable")]),e._v(" interface and delegate to the actual result.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("5")])]),e._v(" "),a("td",[e._v("That wrapper type "),a("code",[e._v("Products")]),e._v(" can be used directly as a query method return type."),a("br"),e._v("You do not need to return "),a("code",[e._v("Streamable<Product>")]),e._v(" and manually wrap it after the query in the repository client.")])])])]),e._v(" "),a("h5",{attrs:{id:"support-for-vavr-collections"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#support-for-vavr-collections"}},[e._v("#")]),e._v(" Support for Vavr Collections")]),e._v(" "),a("p",[a("a",{attrs:{href:"https://www.vavr.io/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Vavr"),a("OutboundLink")],1),e._v(" is a library that embraces functional programming concepts in Java.\nIt ships with a custom set of collection types that you can use as query method return types, as the following table shows:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Vavr collection type")]),e._v(" "),a("th",[e._v("Used Vavr implementation type")]),e._v(" "),a("th",[e._v("Valid Java source types")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("io.vavr.collection.Seq")])]),e._v(" "),a("td",[a("code",[e._v("io.vavr.collection.List")])]),e._v(" "),a("td",[a("code",[e._v("java.util.Iterable")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("io.vavr.collection.Set")])]),e._v(" "),a("td",[a("code",[e._v("io.vavr.collection.LinkedHashSet")])]),e._v(" "),a("td",[a("code",[e._v("java.util.Iterable")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("io.vavr.collection.Map")])]),e._v(" "),a("td",[a("code",[e._v("io.vavr.collection.LinkedHashMap")])]),e._v(" "),a("td",[a("code",[e._v("java.util.Map")])])])])]),e._v(" "),a("p",[e._v("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).\nAlternatively, you can declare "),a("code",[e._v("Traversable")]),e._v(" (the Vavr "),a("code",[e._v("Iterable")]),e._v(" equivalent), and we then derive the implementation class from the actual return value.\nThat is, a "),a("code",[e._v("java.util.List")]),e._v(" is turned into a Vavr "),a("code",[e._v("List")]),e._v(" or "),a("code",[e._v("Seq")]),e._v(", a "),a("code",[e._v("java.util.Set")]),e._v(" becomes a Vavr "),a("code",[e._v("LinkedHashSet")]),e._v(" "),a("code",[e._v("Set")]),e._v(", and so on.")]),e._v(" "),a("h4",{attrs:{id:"_4-4-7-null-handling-of-repository-methods"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-7-null-handling-of-repository-methods"}},[e._v("#")]),e._v(" 4.4.7. Null Handling of Repository Methods")]),e._v(" "),a("p",[e._v("As of Spring Data 2.0, repository CRUD methods that return an individual aggregate instance use Java 8’s "),a("code",[e._v("Optional")]),e._v(" to indicate the potential absence of a value.\nBesides that, Spring Data supports returning the following wrapper types on query methods:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("com.google.common.base.Optional")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("scala.Option")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("io.vavr.control.Option")])])])]),e._v(" "),a("p",[e._v("Alternatively, query methods can choose not to use a wrapper type at all.\nThe absence of a query result is then indicated by returning "),a("code",[e._v("null")]),e._v(".\nRepository methods returning collections, collection alternatives, wrappers, and streams are guaranteed never to return "),a("code",[e._v("null")]),e._v(" but rather the corresponding empty representation.\nSee “"),a("a",{attrs:{href:"#repository-query-return-types"}},[e._v("Repository query return types")]),e._v("” for details.")]),e._v(" "),a("h5",{attrs:{id:"nullability-annotations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#nullability-annotations"}},[e._v("#")]),e._v(" Nullability Annotations")]),e._v(" "),a("p",[e._v("You can express nullability constraints for repository methods by using "),a("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#null-safety",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Framework’s nullability annotations"),a("OutboundLink")],1),e._v(".\nThey provide a tooling-friendly approach and opt-in "),a("code",[e._v("null")]),e._v(" checks during runtime, as follows:")]),e._v(" "),a("ul",[a("li",[a("p",[a("a",{attrs:{href:"https://docs.spring.io/spring/docs/5.3.16/javadoc-api/org/springframework/lang/NonNullApi.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("@NonNullApi")]),a("OutboundLink")],1),e._v(": Used on the package level to declare that the default behavior for parameters and return values is, respectively, neither to accept nor to produce "),a("code",[e._v("null")]),e._v(" values.")])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"https://docs.spring.io/spring/docs/5.3.16/javadoc-api/org/springframework/lang/NonNull.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("@NonNull")]),a("OutboundLink")],1),e._v(": Used on a parameter or return value that must not be "),a("code",[e._v("null")]),e._v(" (not needed on a parameter and return value where "),a("code",[e._v("@NonNullApi")]),e._v(" applies).")])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"https://docs.spring.io/spring/docs/5.3.16/javadoc-api/org/springframework/lang/Nullable.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("@Nullable")]),a("OutboundLink")],1),e._v(": Used on a parameter or return value that can be "),a("code",[e._v("null")]),e._v(".")])])]),e._v(" "),a("p",[e._v("Spring annotations are meta-annotated with "),a("a",{attrs:{href:"https://jcp.org/en/jsr/detail?id=305",target:"_blank",rel:"noopener noreferrer"}},[e._v("JSR 305"),a("OutboundLink")],1),e._v(" annotations (a dormant but widely used JSR).\nJSR 305 meta-annotations let tooling vendors (such as "),a("a",{attrs:{href:"https://www.jetbrains.com/help/idea/nullable-and-notnull-annotations.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("IDEA"),a("OutboundLink")],1),e._v(", "),a("a",{attrs:{href:"https://help.eclipse.org/oxygen/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/task-using_external_null_annotations.htm",target:"_blank",rel:"noopener noreferrer"}},[e._v("Eclipse"),a("OutboundLink")],1),e._v(", and "),a("a",{attrs:{href:"https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types",target:"_blank",rel:"noopener noreferrer"}},[e._v("Kotlin"),a("OutboundLink")],1),e._v(") provide null-safety support in a generic way, without having to hard-code support for Spring annotations.\nTo enable runtime checking of nullability constraints for query methods, you need to activate non-nullability on the package level by using Spring’s "),a("code",[e._v("@NonNullApi")]),e._v(" in "),a("code",[e._v("package-info.java")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 22. Declaring Non-nullability in "),a("code",[e._v("package-info.java")])]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@org.springframework.lang.NonNullApi\npackage com.acme;\n")])])]),a("p",[e._v("Once non-null defaulting is in place, repository query method invocations get validated at runtime for nullability constraints.\nIf a query result violates the defined constraint, an exception is thrown.\nThis happens when the method would return "),a("code",[e._v("null")]),e._v(" but is declared as non-nullable (the default with the annotation defined on the package in which the repository resides).\nIf you want to opt-in to nullable results again, selectively use "),a("code",[e._v("@Nullable")]),e._v(" on individual methods.\nUsing 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.")]),e._v(" "),a("p",[e._v("The following example shows a number of the techniques just described:")]),e._v(" "),a("p",[e._v("Example 23. Using different nullability constraints")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("package com.acme;                                                       (1)\n\nimport org.springframework.lang.Nullable;\n\ninterface UserRepository extends Repository<User, Long> {\n\n  User getByEmailAddress(EmailAddress emailAddress);                    (2)\n\n  @Nullable\n  User findByEmailAddress(@Nullable EmailAddress emailAdress);          (3)\n\n  Optional<User> findOptionalByEmailAddress(EmailAddress emailAddress); (4)\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("The repository resides in a package (or sub-package) for which we have defined non-null behavior.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("Throws an "),a("code",[e._v("EmptyResultDataAccessException")]),e._v(" when the query does not produce a result."),a("br"),e._v("Throws an "),a("code",[e._v("IllegalArgumentException")]),e._v(" when the "),a("code",[e._v("emailAddress")]),e._v(" handed to the method is "),a("code",[e._v("null")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("null")]),e._v(" when the query does not produce a result."),a("br"),e._v("Also accepts "),a("code",[e._v("null")]),e._v(" as the value for "),a("code",[e._v("emailAddress")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("Optional.empty()")]),e._v(" when the query does not produce a result."),a("br"),e._v("Throws an "),a("code",[e._v("IllegalArgumentException")]),e._v(" when the "),a("code",[e._v("emailAddress")]),e._v(" handed to the method is "),a("code",[e._v("null")]),e._v(".")])])])]),e._v(" "),a("h5",{attrs:{id:"nullability-in-kotlin-based-repositories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#nullability-in-kotlin-based-repositories"}},[e._v("#")]),e._v(" Nullability in Kotlin-based Repositories")]),e._v(" "),a("p",[e._v("Kotlin has the definition of "),a("a",{attrs:{href:"https://kotlinlang.org/docs/reference/null-safety.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("nullability constraints"),a("OutboundLink")],1),e._v(" baked into the language.\nKotlin code compiles to bytecode, which does not express nullability constraints through method signatures but rather through compiled-in metadata.\nMake sure to include the "),a("code",[e._v("kotlin-reflect")]),e._v(" JAR in your project to enable introspection of Kotlin’s nullability constraints.\nSpring Data repositories use the language mechanism to define those constraints to apply the same runtime checks, as follows:")]),e._v(" "),a("p",[e._v("Example 24. Using nullability constraints on Kotlin repositories")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository : Repository<User, String> {\n\n  fun findByUsername(username: String): User     (1)\n\n  fun findByFirstname(firstname: String?): User? (2)\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("The method defines both the parameter and the result as non-nullable (the Kotlin default)."),a("br"),e._v("The Kotlin compiler rejects method invocations that pass "),a("code",[e._v("null")]),e._v(" to the method."),a("br"),e._v("If the query yields an empty result, an "),a("code",[e._v("EmptyResultDataAccessException")]),e._v(" is thrown.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("This method accepts "),a("code",[e._v("null")]),e._v(" for the "),a("code",[e._v("firstname")]),e._v(" parameter and returns "),a("code",[e._v("null")]),e._v(" if the query does not produce a result.")])])])]),e._v(" "),a("h4",{attrs:{id:"_4-4-8-streaming-query-results"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-8-streaming-query-results"}},[e._v("#")]),e._v(" 4.4.8. Streaming Query Results")]),e._v(" "),a("p",[e._v("You can process the results of query methods incrementally by using a Java 8 "),a("code",[e._v("Stream<T>")]),e._v(" as the return type.\nInstead of wrapping the query results in a "),a("code",[e._v("Stream")]),e._v(", data store-specific methods are used to perform the streaming, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 25. Stream the result of a query with Java 8 "),a("code",[e._v("Stream<T>")])]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Query("select u from User u")\nStream<User> findAllByCustomQueryAndStream();\n\nStream<User> readAllByFirstnameNotNull();\n\n@Query("select u from User u")\nStream<User> streamAllPaged(Pageable pageable);\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("A "),a("code",[e._v("Stream")]),e._v(" potentially wraps underlying data store-specific resources and must, therefore, be closed after usage."),a("br"),e._v("You can either manually close the "),a("code",[e._v("Stream")]),e._v(" by using the "),a("code",[e._v("close()")]),e._v(" method or by using a Java 7 "),a("code",[e._v("try-with-resources")]),e._v(" block, as shown in the following example:")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Example 26. Working with a "),a("code",[e._v("Stream<T>")]),e._v(" result in a "),a("code",[e._v("try-with-resources")]),e._v(" block")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {\n  stream.forEach(…);\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Not all Spring Data modules currently support "),a("code",[e._v("Stream<T>")]),e._v(" as a return type.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_4-4-9-asynchronous-query-results"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-9-asynchronous-query-results"}},[e._v("#")]),e._v(" 4.4.9. Asynchronous Query Results")]),e._v(" "),a("p",[e._v("You can run repository queries asynchronously by using "),a("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/integration.html#scheduling",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring’s asynchronous method running capability"),a("OutboundLink")],1),e._v(".\nThis means the method returns immediately upon invocation while the actual query occurs in a task that has been submitted to a Spring "),a("code",[e._v("TaskExecutor")]),e._v(".\nAsynchronous queries differ from reactive queries and should not be mixed.\nSee the store-specific documentation for more details on reactive support.\nThe following example shows a number of asynchronous queries:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Async\nFuture<User> findByFirstname(String firstname);               (1)\n\n@Async\nCompletableFuture<User> findOneByFirstname(String firstname); (2)\n\n@Async\nListenableFuture<User> findOneByLastname(String lastname);    (3)\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("Use "),a("code",[e._v("java.util.concurrent.Future")]),e._v(" as the return type.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("Use a Java 8 "),a("code",[e._v("java.util.concurrent.CompletableFuture")]),e._v(" as the return type.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Use a "),a("code",[e._v("org.springframework.util.concurrent.ListenableFuture")]),e._v(" as the return type.")])])])]),e._v(" "),a("h3",{attrs:{id:"_4-5-creating-repository-instances"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-5-creating-repository-instances"}},[e._v("#")]),e._v(" 4.5. Creating Repository Instances")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("h4",{attrs:{id:"_4-5-1-xml-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-5-1-xml-configuration"}},[e._v("#")]),e._v(" 4.5.1. XML Configuration")]),e._v(" "),a("p",[e._v("Each Spring Data module includes a "),a("code",[e._v("repositories")]),e._v(" element that lets you define a base package that Spring scans for you, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 27. Enabling Spring Data repositories via XML")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<?xml version="1.0" encoding="UTF-8"?>\n<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"\n  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n  xmlns="http://www.springframework.org/schema/data/jpa"\n  xsi:schemaLocation="http://www.springframework.org/schema/beans\n    https://www.springframework.org/schema/beans/spring-beans.xsd\n    http://www.springframework.org/schema/data/jpa\n    https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">\n\n  <repositories base-package="com.acme.repositories" />\n\n</beans:beans>\n')])])]),a("p",[e._v("In the preceding example, Spring is instructed to scan "),a("code",[e._v("com.acme.repositories")]),e._v(" and all its sub-packages for interfaces extending "),a("code",[e._v("Repository")]),e._v(" or one of its sub-interfaces.\nFor each interface found, the infrastructure registers the persistence technology-specific "),a("code",[e._v("FactoryBean")]),e._v(" to create the appropriate proxies that handle invocations of the query methods.\nEach bean is registered under a bean name that is derived from the interface name, so an interface of "),a("code",[e._v("UserRepository")]),e._v(" would be registered under "),a("code",[e._v("userRepository")]),e._v(".\nBean names for nested repository interfaces are prefixed with their enclosing type name.\nThe "),a("code",[e._v("base-package")]),e._v(" attribute allows wildcards so that you can define a pattern of scanned packages.")]),e._v(" "),a("h5",{attrs:{id:"using-filters"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#using-filters"}},[e._v("#")]),e._v(" Using Filters")]),e._v(" "),a("p",[e._v("By default, the infrastructure picks up every interface that extends the persistence technology-specific "),a("code",[e._v("Repository")]),e._v(" sub-interface located under the configured base package and creates a bean instance for it.\nHowever, you might want more fine-grained control over which interfaces have bean instances created for them.\nTo do so, use "),a("code",[e._v("<include-filter />")]),e._v(" and "),a("code",[e._v("<exclude-filter />")]),e._v(" elements inside the "),a("code",[e._v("<repositories />")]),e._v(" element.\nThe semantics are exactly equivalent to the elements in Spring’s context namespace.\nFor details, see the "),a("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#beans-scanning-filters",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring reference documentation"),a("OutboundLink")],1),e._v(" for these elements.")]),e._v(" "),a("p",[e._v("For example, to exclude certain interfaces from instantiation as repository beans, you could use the following configuration:")]),e._v(" "),a("p",[e._v("Example 28. Using exclude-filter element")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<repositories base-package="com.acme.repositories">\n  <context:exclude-filter type="regex" expression=".*SomeRepository" />\n</repositories>\n')])])]),a("p",[e._v("The preceding example excludes all interfaces ending in "),a("code",[e._v("SomeRepository")]),e._v(" from being instantiated.")]),e._v(" "),a("h4",{attrs:{id:"_4-5-2-java-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-5-2-java-configuration"}},[e._v("#")]),e._v(" 4.5.2. Java Configuration")]),e._v(" "),a("p",[e._v("You can also trigger the repository infrastructure by using a store-specific "),a("code",[e._v("@Enable${store}Repositories")]),e._v(" annotation on a Java configuration class. For an introduction to Java-based configuration of the Spring container, see "),a("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#beans-java",target:"_blank",rel:"noopener noreferrer"}},[e._v("JavaConfig in the Spring reference documentation"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("A sample configuration to enable Spring Data repositories resembles the following:")]),e._v(" "),a("p",[e._v("Example 29. Sample annotation-based repository configuration")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Configuration\n@EnableJpaRepositories("com.acme.repositories")\nclass ApplicationConfiguration {\n\n  @Bean\n  EntityManagerFactory entityManagerFactory() {\n    // …\n  }\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("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 "),a("code",[e._v("EntityManagerFactory")]),e._v(" bean. See the sections covering the store-specific configuration.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_4-5-3-standalone-usage"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-5-3-standalone-usage"}},[e._v("#")]),e._v(" 4.5.3. Standalone Usage")]),e._v(" "),a("p",[e._v("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 "),a("code",[e._v("RepositoryFactory")]),e._v(" that you can use, as follows:")]),e._v(" "),a("p",[e._v("Example 30. Standalone usage of the repository factory")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("RepositoryFactorySupport factory = … // Instantiate factory here\nUserRepository repository = factory.getRepository(UserRepository.class);\n")])])]),a("h3",{attrs:{id:"_4-6-custom-implementations-for-spring-data-repositories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-6-custom-implementations-for-spring-data-repositories"}},[e._v("#")]),e._v(" 4.6. Custom Implementations for Spring Data Repositories")]),e._v(" "),a("p",[e._v("Spring Data provides various options to create query methods with little coding.\nBut when those options don’t fit your needs you can also provide your own custom implementation for repository methods.\nThis section describes how to do that.")]),e._v(" "),a("h4",{attrs:{id:"_4-6-1-customizing-individual-repositories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-6-1-customizing-individual-repositories"}},[e._v("#")]),e._v(" 4.6.1. Customizing Individual Repositories")]),e._v(" "),a("p",[e._v("To enrich a repository with custom functionality, you must first define a fragment interface and an implementation for the custom functionality, as follows:")]),e._v(" "),a("p",[e._v("Example 31. Interface for custom repository functionality")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface CustomizedUserRepository {\n  void someCustomMethod(User user);\n}\n")])])]),a("p",[e._v("Example 32. Implementation of custom repository functionality")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class CustomizedUserRepositoryImpl implements CustomizedUserRepository {\n\n  public void someCustomMethod(User user) {\n    // Your custom implementation\n  }\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The most important part of the class name that corresponds to the fragment interface is the "),a("code",[e._v("Impl")]),e._v(" postfix.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("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 "),a("code",[e._v("JdbcTemplate")]),e._v("), take part in aspects, and so on.")]),e._v(" "),a("p",[e._v("Then you can let your repository interface extend the fragment interface, as follows:")]),e._v(" "),a("p",[e._v("Example 33. Changes to your repository interface")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {\n\n  // Declare query methods here\n}\n")])])]),a("p",[e._v("Extending the fragment interface with your repository interface combines the CRUD and custom functionality and makes it available to clients.")]),e._v(" "),a("p",[e._v("Spring Data repositories are implemented by using fragments that form a repository composition. Fragments are the base repository, functional aspects (such as "),a("a",{attrs:{href:"#core.extensions.querydsl"}},[e._v("QueryDsl")]),e._v("), 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.")]),e._v(" "),a("p",[e._v("The following example shows custom interfaces and their implementations:")]),e._v(" "),a("p",[e._v("Example 34. Fragments with their implementations")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface HumanRepository {\n  void someHumanMethod(User user);\n}\n\nclass HumanRepositoryImpl implements HumanRepository {\n\n  public void someHumanMethod(User user) {\n    // Your custom implementation\n  }\n}\n\ninterface ContactRepository {\n\n  void someContactMethod(User user);\n\n  User anotherContactMethod(User user);\n}\n\nclass ContactRepositoryImpl implements ContactRepository {\n\n  public void someContactMethod(User user) {\n    // Your custom implementation\n  }\n\n  public User anotherContactMethod(User user) {\n    // Your custom implementation\n  }\n}\n")])])]),a("p",[e._v("The following example shows the interface for a custom repository that extends "),a("code",[e._v("CrudRepository")]),e._v(":")]),e._v(" "),a("p",[e._v("Example 35. Changes to your repository interface")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {\n\n  // Declare query methods here\n}\n")])])]),a("p",[e._v("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.")]),e._v(" "),a("p",[e._v("The following example shows a repository fragment and its implementation:")]),e._v(" "),a("p",[e._v("Example 36. Fragments overriding "),a("code",[e._v("save(…)")])]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface CustomizedSave<T> {\n  <S extends T> S save(S entity);\n}\n\nclass CustomizedSaveImpl<T> implements CustomizedSave<T> {\n\n  public <S extends T> S save(S entity) {\n    // Your custom implementation\n  }\n}\n")])])]),a("p",[e._v("The following example shows a repository that uses the preceding repository fragment:")]),e._v(" "),a("p",[e._v("Example 37. Customized repository interfaces")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {\n}\n\ninterface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {\n}\n")])])]),a("h5",{attrs:{id:"configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#configuration"}},[e._v("#")]),e._v(" Configuration")]),e._v(" "),a("p",[e._v("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.\nThese classes need to follow the naming convention of appending the namespace element’s "),a("code",[e._v("repository-impl-postfix")]),e._v(" attribute to the fragment interface name.\nThis postfix defaults to "),a("code",[e._v("Impl")]),e._v(".\nThe following example shows a repository that uses the default postfix and a repository that sets a custom value for the postfix:")]),e._v(" "),a("p",[e._v("Example 38. Configuration example")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<repositories base-package="com.acme.repository" />\n\n<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />\n')])])]),a("p",[e._v("The first configuration in the preceding example tries to look up a class called "),a("code",[e._v("com.acme.repository.CustomizedUserRepositoryImpl")]),e._v(" to act as a custom repository implementation.\nThe second example tries to look up "),a("code",[e._v("com.acme.repository.CustomizedUserRepositoryMyPostfix")]),e._v(".")]),e._v(" "),a("h6",{attrs:{id:"resolution-of-ambiguity"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#resolution-of-ambiguity"}},[e._v("#")]),e._v(" Resolution of Ambiguity")]),e._v(" "),a("p",[e._v("If multiple implementations with matching class names are found in different packages, Spring Data uses the bean names to identify which one to use.")]),e._v(" "),a("p",[e._v("Given the following two custom implementations for the "),a("code",[e._v("CustomizedUserRepository")]),e._v(" shown earlier, the first implementation is used.\nIts bean name is "),a("code",[e._v("customizedUserRepositoryImpl")]),e._v(", which matches that of the fragment interface ("),a("code",[e._v("CustomizedUserRepository")]),e._v(") plus the postfix "),a("code",[e._v("Impl")]),e._v(".")]),e._v(" "),a("p",[e._v("Example 39. Resolution of ambiguous implementations")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("package com.acme.impl.one;\n\nclass CustomizedUserRepositoryImpl implements CustomizedUserRepository {\n\n  // Your custom implementation\n}\n")])])]),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('package com.acme.impl.two;\n\n@Component("specialCustomImpl")\nclass CustomizedUserRepositoryImpl implements CustomizedUserRepository {\n\n  // Your custom implementation\n}\n')])])]),a("p",[e._v("If you annotate the "),a("code",[e._v("UserRepository")]),e._v(" interface with "),a("code",[e._v('@Component("specialCustom")')]),e._v(", the bean name plus "),a("code",[e._v("Impl")]),e._v(" then matches the one defined for the repository implementation in "),a("code",[e._v("com.acme.impl.two")]),e._v(", and it is used instead of the first one.")]),e._v(" "),a("h6",{attrs:{id:"manual-wiring"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#manual-wiring"}},[e._v("#")]),e._v(" Manual Wiring")]),e._v(" "),a("p",[e._v("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.\nIf your implementation fragment bean needs special wiring, you can declare the bean and name it according to the conventions described in the "),a("a",{attrs:{href:"#repositories.single-repository-behaviour.ambiguity"}},[e._v("preceding section")]),e._v(".\nThe infrastructure then refers to the manually defined bean definition by name instead of creating one itself.\nThe following example shows how to manually wire a custom implementation:")]),e._v(" "),a("p",[e._v("Example 40. Manual wiring of custom implementations")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<repositories base-package="com.acme.repository" />\n\n<beans:bean id="userRepositoryImpl" class="…">\n  \x3c!-- further configuration --\x3e\n</beans:bean>\n')])])]),a("h4",{attrs:{id:"_4-6-2-customize-the-base-repository"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-6-2-customize-the-base-repository"}},[e._v("#")]),e._v(" 4.6.2. Customize the Base Repository")]),e._v(" "),a("p",[e._v("The approach described in the "),a("a",{attrs:{href:"#repositories.manual-wiring"}},[e._v("preceding section")]),e._v(" requires customization of each repository interfaces when you want to customize the base repository behavior so that all repositories are affected.\nTo instead change behavior for all repositories, you can create an implementation that extends the persistence technology-specific repository base class.\nThis class then acts as a custom base class for the repository proxies, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 41. Custom repository base class")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class MyRepositoryImpl<T, ID>\n  extends SimpleJpaRepository<T, ID> {\n\n  private final EntityManager entityManager;\n\n  MyRepositoryImpl(JpaEntityInformation entityInformation,\n                          EntityManager entityManager) {\n    super(entityInformation, entityManager);\n\n    // Keep the EntityManager around to used from the newly introduced methods.\n    this.entityManager = entityManager;\n  }\n\n  @Transactional\n  public <S extends T> S save(S entity) {\n    // implementation goes here\n  }\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The class needs to have a constructor of the super class which the store-specific repository factory implementation uses."),a("br"),e._v("If the repository base class has multiple constructors, override the one taking an "),a("code",[e._v("EntityInformation")]),e._v(" plus a store specific infrastructure object (such as an "),a("code",[e._v("EntityManager")]),e._v(" or a template class).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The final step is to make the Spring Data infrastructure aware of the customized repository base class.\nIn Java configuration, you can do so by using the "),a("code",[e._v("repositoryBaseClass")]),e._v(" attribute of the "),a("code",[e._v("@Enable${store}Repositories")]),e._v(" annotation, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 42. Configuring a custom repository base class using JavaConfig")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Configuration\n@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)\nclass ApplicationConfiguration { … }\n")])])]),a("p",[e._v("A corresponding attribute is available in the XML namespace, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 43. Configuring a custom repository base class using XML")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<repositories base-package="com.acme.repository"\n     base-class="….MyRepositoryImpl" />\n')])])]),a("h3",{attrs:{id:"_4-7-publishing-events-from-aggregate-roots"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-7-publishing-events-from-aggregate-roots"}},[e._v("#")]),e._v(" 4.7. Publishing Events from Aggregate Roots")]),e._v(" "),a("p",[e._v("Entities managed by repositories are aggregate roots.\nIn a Domain-Driven Design application, these aggregate roots usually publish domain events.\nSpring Data provides an annotation called "),a("code",[e._v("@DomainEvents")]),e._v(" 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:")]),e._v(" "),a("p",[e._v("Example 44. Exposing domain events from an aggregate root")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class AnAggregateRoot {\n\n    @DomainEvents (1)\n    Collection<Object> domainEvents() {\n        // … return events you want to get published here\n    }\n\n    @AfterDomainEventPublication (2)\n    void callbackMethod() {\n       // … potentially clean up domain events list\n    }\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("The method that uses "),a("code",[e._v("@DomainEvents")]),e._v(" can return either a single event instance or a collection of events."),a("br"),e._v("It must not take any arguments.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("After all events have been published, we have a method annotated with "),a("code",[e._v("@AfterDomainEventPublication")]),e._v("."),a("br"),e._v("You can use it to potentially clean the list of events to be published (among other uses).")])])])]),e._v(" "),a("p",[e._v("The methods are called every time one of a Spring Data repository’s "),a("code",[e._v("save(…)")]),e._v(", "),a("code",[e._v("saveAll(…)")]),e._v(", "),a("code",[e._v("delete(…)")]),e._v(" or "),a("code",[e._v("deleteAll(…)")]),e._v(" methods are called.")]),e._v(" "),a("h3",{attrs:{id:"_4-8-spring-data-extensions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-8-spring-data-extensions"}},[e._v("#")]),e._v(" 4.8. Spring Data Extensions")]),e._v(" "),a("p",[e._v("This section documents a set of Spring Data extensions that enable Spring Data usage in a variety of contexts.\nCurrently, most of the integration is targeted towards Spring MVC.")]),e._v(" "),a("h4",{attrs:{id:"_4-8-1-querydsl-extension"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-8-1-querydsl-extension"}},[e._v("#")]),e._v(" 4.8.1. Querydsl Extension")]),e._v(" "),a("p",[a("a",{attrs:{href:"http://www.querydsl.com/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Querydsl"),a("OutboundLink")],1),e._v(" is a framework that enables the construction of statically typed SQL-like queries through its fluent API.")]),e._v(" "),a("p",[e._v("Several Spring Data modules offer integration with Querydsl through "),a("code",[e._v("QuerydslPredicateExecutor")]),e._v(", as the following example shows:")]),e._v(" "),a("p",[e._v("Example 45. QuerydslPredicateExecutor interface")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public interface QuerydslPredicateExecutor<T> {\n\n  Optional<T> findById(Predicate predicate);  (1)\n\n  Iterable<T> findAll(Predicate predicate);   (2)\n\n  long count(Predicate predicate);            (3)\n\n  boolean exists(Predicate predicate);        (4)\n\n  // … more functionality omitted.\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("Finds and returns a single entity matching the "),a("code",[e._v("Predicate")]),e._v(".")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("Finds and returns all entities matching the "),a("code",[e._v("Predicate")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Returns the number of entities matching the "),a("code",[e._v("Predicate")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Returns whether an entity that matches the "),a("code",[e._v("Predicate")]),e._v(" exists.")])])])]),e._v(" "),a("p",[e._v("To use the Querydsl support, extend "),a("code",[e._v("QuerydslPredicateExecutor")]),e._v(" on your repository interface, as the following example shows:")]),e._v(" "),a("p",[e._v("Example 46. Querydsl integration on repositories")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, Long>, QuerydslPredicateExecutor<User> {\n}\n")])])]),a("p",[e._v("The preceding example lets you write type-safe queries by using Querydsl "),a("code",[e._v("Predicate")]),e._v(" instances, as the following example shows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('Predicate predicate = user.firstname.equalsIgnoreCase("dave")\n\t.and(user.lastname.startsWithIgnoreCase("mathews"));\n\nuserRepository.findAll(predicate);\n')])])]),a("h4",{attrs:{id:"_4-8-2-web-support"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-8-2-web-support"}},[e._v("#")]),e._v(" 4.8.2. Web support")]),e._v(" "),a("p",[e._v("Spring Data modules that support the repository programming model ship with a variety of web support.\nThe web related components require Spring MVC JARs to be on the classpath.\nSome of them even provide integration with "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-hateoas",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring HATEOAS"),a("OutboundLink")],1),e._v(".\nIn general, the integration support is enabled by using the "),a("code",[e._v("@EnableSpringDataWebSupport")]),e._v(" annotation in your JavaConfig configuration class, as the following example shows:")]),e._v(" "),a("p",[e._v("Example 47. Enabling Spring Data web support")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Configuration\n@EnableWebMvc\n@EnableSpringDataWebSupport\nclass WebConfiguration {}\n")])])]),a("p",[e._v("The "),a("code",[e._v("@EnableSpringDataWebSupport")]),e._v(" annotation registers a few components.\nWe discuss those later in this section.\nIt also detects Spring HATEOAS on the classpath and registers integration components (if present) for it as well.")]),e._v(" "),a("p",[e._v("Alternatively, if you use XML configuration, register either "),a("code",[e._v("SpringDataWebConfiguration")]),e._v(" or "),a("code",[e._v("HateoasAwareSpringDataWebConfiguration")]),e._v(" as Spring beans, as the following example shows (for "),a("code",[e._v("SpringDataWebConfiguration")]),e._v("):")]),e._v(" "),a("p",[e._v("Example 48. Enabling Spring Data web support in XML")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<bean class="org.springframework.data.web.config.SpringDataWebConfiguration" />\n\n\x3c!-- If you use Spring HATEOAS, register this one *instead* of the former --\x3e\n<bean class="org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration" />\n')])])]),a("h5",{attrs:{id:"basic-web-support"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#basic-web-support"}},[e._v("#")]),e._v(" Basic Web Support")]),e._v(" "),a("p",[e._v("The configuration shown in the "),a("a",{attrs:{href:"#core.web"}},[e._v("previous section")]),e._v(" registers a few basic components:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("A "),a("a",{attrs:{href:"#core.web.basic.domain-class-converter"}},[e._v("Using the "),a("code",[e._v("DomainClassConverter")]),e._v(" Class")]),e._v(" to let Spring MVC resolve instances of repository-managed domain classes from request parameters or path variables.")])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#core.web.basic.paging-and-sorting"}},[a("code",[e._v("HandlerMethodArgumentResolver")])]),e._v(" implementations to let Spring MVC resolve "),a("code",[e._v("Pageable")]),e._v(" and "),a("code",[e._v("Sort")]),e._v(" instances from request parameters.")])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#core.web.basic.jackson-mappers"}},[e._v("Jackson Modules")]),e._v(" to de-/serialize types like "),a("code",[e._v("Point")]),e._v(" and "),a("code",[e._v("Distance")]),e._v(", or store specific ones, depending on the Spring Data Module used.")])])]),e._v(" "),a("h6",{attrs:{id:"using-the-domainclassconverter-class"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#using-the-domainclassconverter-class"}},[e._v("#")]),e._v(" Using the "),a("code",[e._v("DomainClassConverter")]),e._v(" Class")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("DomainClassConverter")]),e._v(" 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:")]),e._v(" "),a("p",[e._v("Example 49. A Spring MVC controller using domain types in method signatures")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Controller\n@RequestMapping("/users")\nclass UserController {\n\n  @RequestMapping("/{id}")\n  String showUserForm(@PathVariable("id") User user, Model model) {\n\n    model.addAttribute("user", user);\n    return "userForm";\n  }\n}\n')])])]),a("p",[e._v("The method receives a "),a("code",[e._v("User")]),e._v(" instance directly, and no further lookup is necessary.\nThe instance can be resolved by letting Spring MVC convert the path variable into the "),a("code",[e._v("id")]),e._v(" type of the domain class first and eventually access the instance through calling "),a("code",[e._v("findById(…)")]),e._v(" on the repository instance registered for the domain type.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Currently, the repository has to implement "),a("code",[e._v("CrudRepository")]),e._v(" to be eligible to be discovered for conversion.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h6",{attrs:{id:"handlermethodargumentresolvers-for-pageable-and-sort"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#handlermethodargumentresolvers-for-pageable-and-sort"}},[e._v("#")]),e._v(" HandlerMethodArgumentResolvers for Pageable and Sort")]),e._v(" "),a("p",[e._v("The configuration snippet shown in the "),a("a",{attrs:{href:"#core.web.basic.domain-class-converter"}},[e._v("previous section")]),e._v(" also registers a "),a("code",[e._v("PageableHandlerMethodArgumentResolver")]),e._v(" as well as an instance of "),a("code",[e._v("SortHandlerMethodArgumentResolver")]),e._v(".\nThe registration enables "),a("code",[e._v("Pageable")]),e._v(" and "),a("code",[e._v("Sort")]),e._v(" as valid controller method arguments, as the following example shows:")]),e._v(" "),a("p",[e._v("Example 50. Using Pageable as a controller method argument")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Controller\n@RequestMapping("/users")\nclass UserController {\n\n  private final UserRepository repository;\n\n  UserController(UserRepository repository) {\n    this.repository = repository;\n  }\n\n  @RequestMapping\n  String showUsers(Model model, Pageable pageable) {\n\n    model.addAttribute("users", repository.findAll(pageable));\n    return "users";\n  }\n}\n')])])]),a("p",[e._v("The preceding method signature causes Spring MVC try to derive a "),a("code",[e._v("Pageable")]),e._v(" instance from the request parameters by using the following default configuration:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[a("code",[e._v("page")])]),e._v(" "),a("th",[e._v("Page you want to retrieve. 0-indexed and defaults to 0.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("size")])]),e._v(" "),a("td",[e._v("Size of the page you want to retrieve. Defaults to 20.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("sort")])]),e._v(" "),a("td",[e._v("Properties that should be sorted by in the format "),a("code",[e._v("property,property(,ASC|DESC)(,IgnoreCase)")]),e._v(". The default sort direction is case-sensitive ascending. Use multiple "),a("code",[e._v("sort")]),e._v(" parameters if you want to switch direction or case sensitivity — for example, "),a("code",[e._v("?sort=firstname&sort=lastname,asc&sort=city,ignorecase")]),e._v(".")])])])]),e._v(" "),a("p",[e._v("To customize this behavior, register a bean that implements the "),a("code",[e._v("PageableHandlerMethodArgumentResolverCustomizer")]),e._v(" interface or the "),a("code",[e._v("SortHandlerMethodArgumentResolverCustomizer")]),e._v(" interface, respectively.\nIts "),a("code",[e._v("customize()")]),e._v(" method gets called, letting you change settings, as the following example shows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {\n    return s -> s.setPropertyDelimiter("<--\x3e");\n}\n')])])]),a("p",[e._v("If setting the properties of an existing "),a("code",[e._v("MethodArgumentResolver")]),e._v(" is not sufficient for your purpose, extend either "),a("code",[e._v("SpringDataWebConfiguration")]),e._v(" or the HATEOAS-enabled equivalent, override the "),a("code",[e._v("pageableResolver()")]),e._v(" or "),a("code",[e._v("sortResolver()")]),e._v(" methods, and import your customized configuration file instead of using the "),a("code",[e._v("@Enable")]),e._v(" annotation.")]),e._v(" "),a("p",[e._v("If you need multiple "),a("code",[e._v("Pageable")]),e._v(" or "),a("code",[e._v("Sort")]),e._v(" instances to be resolved from the request (for multiple tables, for example), you can use Spring’s "),a("code",[e._v("@Qualifier")]),e._v(" annotation to distinguish one from another.\nThe request parameters then have to be prefixed with "),a("code",[e._v("${qualifier}_")]),e._v(".\nThe following example shows the resulting method signature:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('String showUsers(Model model,\n      @Qualifier("thing1") Pageable first,\n      @Qualifier("thing2") Pageable second) { … }\n')])])]),a("p",[e._v("You have to populate "),a("code",[e._v("thing1_page")]),e._v(", "),a("code",[e._v("thing2_page")]),e._v(", and so on.")]),e._v(" "),a("p",[e._v("The default "),a("code",[e._v("Pageable")]),e._v(" passed into the method is equivalent to a "),a("code",[e._v("PageRequest.of(0, 20)")]),e._v(", but you can customize it by using the "),a("code",[e._v("@PageableDefault")]),e._v(" annotation on the "),a("code",[e._v("Pageable")]),e._v(" parameter.")]),e._v(" "),a("h5",{attrs:{id:"hypermedia-support-for-pageables"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#hypermedia-support-for-pageables"}},[e._v("#")]),e._v(" Hypermedia Support for Pageables")]),e._v(" "),a("p",[e._v("Spring HATEOAS ships with a representation model class ("),a("code",[e._v("PagedResources")]),e._v(") that allows enriching the content of a "),a("code",[e._v("Page")]),e._v(" instance with the necessary "),a("code",[e._v("Page")]),e._v(" metadata as well as links to let the clients easily navigate the pages.\nThe conversion of a "),a("code",[e._v("Page")]),e._v(" to a "),a("code",[e._v("PagedResources")]),e._v(" is done by an implementation of the Spring HATEOAS "),a("code",[e._v("ResourceAssembler")]),e._v(" interface, called the "),a("code",[e._v("PagedResourcesAssembler")]),e._v(".\nThe following example shows how to use a "),a("code",[e._v("PagedResourcesAssembler")]),e._v(" as a controller method argument:")]),e._v(" "),a("p",[e._v("Example 51. Using a PagedResourcesAssembler as controller method argument")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Controller\nclass PersonController {\n\n  @Autowired PersonRepository repository;\n\n  @RequestMapping(value = "/persons", method = RequestMethod.GET)\n  HttpEntity<PagedResources<Person>> persons(Pageable pageable,\n    PagedResourcesAssembler assembler) {\n\n    Page<Person> persons = repository.findAll(pageable);\n    return new ResponseEntity<>(assembler.toResources(persons), HttpStatus.OK);\n  }\n}\n')])])]),a("p",[e._v("Enabling the configuration, as shown in the preceding example, lets the "),a("code",[e._v("PagedResourcesAssembler")]),e._v(" be used as a controller method argument.\nCalling "),a("code",[e._v("toResources(…)")]),e._v(" on it has the following effects:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("The content of the "),a("code",[e._v("Page")]),e._v(" becomes the content of the "),a("code",[e._v("PagedResources")]),e._v(" instance.")])]),e._v(" "),a("li",[a("p",[e._v("The "),a("code",[e._v("PagedResources")]),e._v(" object gets a "),a("code",[e._v("PageMetadata")]),e._v(" instance attached, and it is populated with information from the "),a("code",[e._v("Page")]),e._v(" and the underlying "),a("code",[e._v("PageRequest")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("The "),a("code",[e._v("PagedResources")]),e._v(" may get "),a("code",[e._v("prev")]),e._v(" and "),a("code",[e._v("next")]),e._v(" links attached, depending on the page’s state.\nThe links point to the URI to which the method maps.\nThe pagination parameters added to the method match the setup of the "),a("code",[e._v("PageableHandlerMethodArgumentResolver")]),e._v(" to make sure the links can be resolved later.")])])]),e._v(" "),a("p",[e._v("Assume we have 30 "),a("code",[e._v("Person")]),e._v(" instances in the database.\nYou can now trigger a request ("),a("code",[e._v("GET [http://localhost:8080/persons](http://localhost:8080/persons)")]),e._v(") and see output similar to the following:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('{ "links" : [ { "rel" : "next",\n                "href" : "http://localhost:8080/persons?page=1&size=20" }\n  ],\n  "content" : [\n     … // 20 Person instances rendered here\n  ],\n  "pageMetadata" : {\n    "size" : 20,\n    "totalElements" : 30,\n    "totalPages" : 2,\n    "number" : 0\n  }\n}\n')])])]),a("p",[e._v("The assembler produced the correct URI and also picked up the default configuration to resolve the parameters into a "),a("code",[e._v("Pageable")]),e._v(" for an upcoming request.\nThis means that, if you change that configuration, the links automatically adhere to the change.\nBy default, the assembler points to the controller method it was invoked in, but you can customize that by passing a custom "),a("code",[e._v("Link")]),e._v(" to be used as base to build the pagination links, which overloads the "),a("code",[e._v("PagedResourcesAssembler.toResource(…)")]),e._v(" method.")]),e._v(" "),a("h5",{attrs:{id:"spring-data-jackson-modules"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#spring-data-jackson-modules"}},[e._v("#")]),e._v(" Spring Data Jackson Modules")]),e._v(" "),a("p",[e._v("The core module, and some of the store specific ones, ship with a set of Jackson Modules for types, like "),a("code",[e._v("org.springframework.data.geo.Distance")]),e._v(" and "),a("code",[e._v("org.springframework.data.geo.Point")]),e._v(", used by the Spring Data domain."),a("br"),e._v("\nThose Modules are imported once "),a("a",{attrs:{href:"#core.web"}},[e._v("web support")]),e._v(" is enabled and "),a("code",[e._v("com.fasterxml.jackson.databind.ObjectMapper")]),e._v(" is available.")]),e._v(" "),a("p",[e._v("During initialization "),a("code",[e._v("SpringDataJacksonModules")]),e._v(", like the "),a("code",[e._v("SpringDataJacksonConfiguration")]),e._v(", get picked up by the infrastructure, so that the declared "),a("code",[e._v("com.fasterxml.jackson.databind.Module")]),e._v("s are made available to the Jackson "),a("code",[e._v("ObjectMapper")]),e._v(".")]),e._v(" "),a("p",[e._v("Data binding mixins for the following domain types are registered by the common infrastructure.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("org.springframework.data.geo.Distance\norg.springframework.data.geo.Point\norg.springframework.data.geo.Box\norg.springframework.data.geo.Circle\norg.springframework.data.geo.Polygon\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The individual module may provide additional "),a("code",[e._v("SpringDataJacksonModules")]),e._v(".  "),a("br"),e._v("Please refer to the store specific section for more details.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h5",{attrs:{id:"web-databinding-support"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#web-databinding-support"}},[e._v("#")]),e._v(" Web Databinding Support")]),e._v(" "),a("p",[e._v("You can use Spring Data projections (described in "),a("a",{attrs:{href:"#projections"}},[e._v("Projections")]),e._v(") to bind incoming request payloads by using either "),a("a",{attrs:{href:"https://goessner.net/articles/JsonPath/",target:"_blank",rel:"noopener noreferrer"}},[e._v("JSONPath"),a("OutboundLink")],1),e._v(" expressions (requires "),a("a",{attrs:{href:"https://github.com/json-path/JsonPath",target:"_blank",rel:"noopener noreferrer"}},[e._v("Jayway JsonPath"),a("OutboundLink")],1),e._v(" or "),a("a",{attrs:{href:"https://www.w3.org/TR/xpath-31/",target:"_blank",rel:"noopener noreferrer"}},[e._v("XPath"),a("OutboundLink")],1),e._v(" expressions (requires "),a("a",{attrs:{href:"https://xmlbeam.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("XmlBeam"),a("OutboundLink")],1),e._v("), as the following example shows:")]),e._v(" "),a("p",[e._v("Example 52. HTTP payload binding using JSONPath or XPath expressions")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@ProjectedPayload\npublic interface UserPayload {\n\n  @XBRead("//firstname")\n  @JsonPath("$..firstname")\n  String getFirstname();\n\n  @XBRead("/lastname")\n  @JsonPath({ "$.lastname", "$.user.lastname" })\n  String getLastname();\n}\n')])])]),a("p",[e._v("You can use the type shown in the preceding example as a Spring MVC handler method argument or by using "),a("code",[e._v("ParameterizedTypeReference")]),e._v(" on one of methods of the "),a("code",[e._v("RestTemplate")]),e._v(".\nThe preceding method declarations would try to find "),a("code",[e._v("firstname")]),e._v(" anywhere in the given document.\nThe "),a("code",[e._v("lastname")]),e._v(" XML lookup is performed on the top-level of the incoming document.\nThe JSON variant of that tries a top-level "),a("code",[e._v("lastname")]),e._v(" first but also tries "),a("code",[e._v("lastname")]),e._v(" nested in a "),a("code",[e._v("user")]),e._v(" sub-document if the former does not return a value.\nThat 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).")]),e._v(" "),a("p",[e._v("Nested projections are supported as described in "),a("a",{attrs:{href:"#projections"}},[e._v("Projections")]),e._v(".\nIf the method returns a complex, non-interface type, a Jackson "),a("code",[e._v("ObjectMapper")]),e._v(" is used to map the final value.")]),e._v(" "),a("p",[e._v("For Spring MVC, the necessary converters are registered automatically as soon as "),a("code",[e._v("@EnableSpringDataWebSupport")]),e._v(" is active and the required dependencies are available on the classpath.\nFor usage with "),a("code",[e._v("RestTemplate")]),e._v(", register a "),a("code",[e._v("ProjectingJackson2HttpMessageConverter")]),e._v(" (JSON) or "),a("code",[e._v("XmlBeamHttpMessageConverter")]),e._v(" manually.")]),e._v(" "),a("p",[e._v("For more information, see the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-data-examples/tree/master/web/projection",target:"_blank",rel:"noopener noreferrer"}},[e._v("web projection example"),a("OutboundLink")],1),e._v(" in the canonical "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-data-examples",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Data Examples repository"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h5",{attrs:{id:"querydsl-web-support"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#querydsl-web-support"}},[e._v("#")]),e._v(" Querydsl Web Support")]),e._v(" "),a("p",[e._v("For those stores that have "),a("a",{attrs:{href:"http://www.querydsl.com/",target:"_blank",rel:"noopener noreferrer"}},[e._v("QueryDSL"),a("OutboundLink")],1),e._v(" integration, you can derive queries from the attributes contained in a "),a("code",[e._v("Request")]),e._v(" query string.")]),e._v(" "),a("p",[e._v("Consider the following query string:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("?firstname=Dave&lastname=Matthews\n")])])]),a("p",[e._v("Given the "),a("code",[e._v("User")]),e._v(" object from the previous examples, you can resolve a query string to the following value by using the "),a("code",[e._v("QuerydslPredicateArgumentResolver")]),e._v(", as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('QUser.user.firstname.eq("Dave").and(QUser.user.lastname.eq("Matthews"))\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The feature is automatically enabled, along with "),a("code",[e._v("@EnableSpringDataWebSupport")]),e._v(", when Querydsl is found on the classpath.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Adding a "),a("code",[e._v("@QuerydslPredicate")]),e._v(" to the method signature provides a ready-to-use "),a("code",[e._v("Predicate")]),e._v(", which you can run by using the "),a("code",[e._v("QuerydslPredicateExecutor")]),e._v(".")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Type information is typically resolved from the method’s return type."),a("br"),e._v("Since that information does not necessarily match the domain type, it might be a good idea to use the "),a("code",[e._v("root")]),e._v(" attribute of "),a("code",[e._v("QuerydslPredicate")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The following example shows how to use "),a("code",[e._v("@QuerydslPredicate")]),e._v(" in a method signature:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Controller\nclass UserController {\n\n  @Autowired UserRepository repository;\n\n  @RequestMapping(value = "/", method = RequestMethod.GET)\n  String index(Model model, @QuerydslPredicate(root = User.class) Predicate predicate,    (1)\n          Pageable pageable, @RequestParam MultiValueMap<String, String> parameters) {\n\n    model.addAttribute("users", repository.findAll(predicate, pageable));\n\n    return "index";\n  }\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("Resolve query string arguments to matching "),a("code",[e._v("Predicate")]),e._v(" for "),a("code",[e._v("User")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The default binding is as follows:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("Object")]),e._v(" on simple properties as "),a("code",[e._v("eq")]),e._v(".")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("Object")]),e._v(" on collection like properties as "),a("code",[e._v("contains")]),e._v(".")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("Collection")]),e._v(" on simple properties as "),a("code",[e._v("in")]),e._v(".")])])]),e._v(" "),a("p",[e._v("You can customize those bindings through the "),a("code",[e._v("bindings")]),e._v(" attribute of "),a("code",[e._v("@QuerydslPredicate")]),e._v(" or by making use of Java 8 "),a("code",[e._v("default methods")]),e._v(" and adding the "),a("code",[e._v("QuerydslBinderCustomizer")]),e._v(" method to the repository interface, as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface UserRepository extends CrudRepository<User, String>,\n                                 QuerydslPredicateExecutor<User>,                (1)\n                                 QuerydslBinderCustomizer<QUser> {               (2)\n\n  @Override\n  default void customize(QuerydslBindings bindings, QUser user) {\n\n    bindings.bind(user.username).first((path, value) -> path.contains(value))    (3)\n    bindings.bind(String.class)\n      .first((StringPath path, String value) -> path.containsIgnoreCase(value)); (4)\n    bindings.excluding(user.password);                                           (5)\n  }\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[a("code",[e._v("QuerydslPredicateExecutor")]),e._v(" provides access to specific finder methods for "),a("code",[e._v("Predicate")]),e._v(".")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[a("code",[e._v("QuerydslBinderCustomizer")]),e._v(" defined on the repository interface is automatically picked up and shortcuts "),a("code",[e._v("@QuerydslPredicate(bindings=…​)")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Define the binding for the "),a("code",[e._v("username")]),e._v(" property to be a simple "),a("code",[e._v("contains")]),e._v(" binding.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Define the default binding for "),a("code",[e._v("String")]),e._v(" properties to be a case-insensitive "),a("code",[e._v("contains")]),e._v(" match.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("5")])]),e._v(" "),a("td",[e._v("Exclude the "),a("code",[e._v("password")]),e._v(" property from "),a("code",[e._v("Predicate")]),e._v(" resolution.")])])])]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("You can register a "),a("code",[e._v("QuerydslBinderCustomizerDefaults")]),e._v(" bean holding default Querydsl bindings before applying specific bindings from the repository or "),a("code",[e._v("@QuerydslPredicate")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_4-8-3-repository-populators"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-8-3-repository-populators"}},[e._v("#")]),e._v(" 4.8.3. Repository Populators")]),e._v(" "),a("p",[e._v("If you work with the Spring JDBC module, you are probably familiar with the support for populating a "),a("code",[e._v("DataSource")]),e._v(" with SQL scripts.\nA 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.\nThus, the populators support XML (through Spring’s OXM abstraction) and JSON (through Jackson) to define data with which to populate the repositories.")]),e._v(" "),a("p",[e._v("Assume you have a file called "),a("code",[e._v("data.json")]),e._v(" with the following content:")]),e._v(" "),a("p",[e._v("Example 53. Data defined in JSON")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('[ { "_class" : "com.acme.Person",\n "firstname" : "Dave",\n  "lastname" : "Matthews" },\n  { "_class" : "com.acme.Person",\n "firstname" : "Carter",\n  "lastname" : "Beauford" } ]\n')])])]),a("p",[e._v("You can populate your repositories by using the populator elements of the repository namespace provided in Spring Data Commons.\nTo populate the preceding data to your "),a("code",[e._v("PersonRepository")]),e._v(", declare a populator similar to the following:")]),e._v(" "),a("p",[e._v("Example 54. Declaring a Jackson repository populator")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<?xml version="1.0" encoding="UTF-8"?>\n<beans xmlns="http://www.springframework.org/schema/beans"\n  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n  xmlns:repository="http://www.springframework.org/schema/data/repository"\n  xsi:schemaLocation="http://www.springframework.org/schema/beans\n    https://www.springframework.org/schema/beans/spring-beans.xsd\n    http://www.springframework.org/schema/data/repository\n    https://www.springframework.org/schema/data/repository/spring-repository.xsd">\n\n  <repository:jackson2-populator locations="classpath:data.json" />\n\n</beans>\n')])])]),a("p",[e._v("The preceding declaration causes the "),a("code",[e._v("data.json")]),e._v(" file to be read and deserialized by a Jackson "),a("code",[e._v("ObjectMapper")]),e._v(".")]),e._v(" "),a("p",[e._v("The type to which the JSON object is unmarshalled is determined by inspecting the "),a("code",[e._v("_class")]),e._v(" attribute of the JSON document.\nThe infrastructure eventually selects the appropriate repository to handle the object that was deserialized.")]),e._v(" "),a("p",[e._v("To instead use XML to define the data the repositories should be populated with, you can use the "),a("code",[e._v("unmarshaller-populator")]),e._v(" element.\nYou configure it to use one of the XML marshaller options available in Spring OXM. See the "),a("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/data-access.html#oxm",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring reference documentation"),a("OutboundLink")],1),e._v(" for details.\nThe following example shows how to unmarshall a repository populator with JAXB:")]),e._v(" "),a("p",[e._v("Example 55. Declaring an unmarshalling repository populator (using JAXB)")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<?xml version="1.0" encoding="UTF-8"?>\n<beans xmlns="http://www.springframework.org/schema/beans"\n  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n  xmlns:repository="http://www.springframework.org/schema/data/repository"\n  xmlns:oxm="http://www.springframework.org/schema/oxm"\n  xsi:schemaLocation="http://www.springframework.org/schema/beans\n    https://www.springframework.org/schema/beans/spring-beans.xsd\n    http://www.springframework.org/schema/data/repository\n    https://www.springframework.org/schema/data/repository/spring-repository.xsd\n    http://www.springframework.org/schema/oxm\n    https://www.springframework.org/schema/oxm/spring-oxm.xsd">\n\n  <repository:unmarshaller-populator locations="classpath:data.json"\n    unmarshaller-ref="unmarshaller" />\n\n  <oxm:jaxb2-marshaller contextPath="com.acme" />\n\n</beans>\n')])])]),a("h2",{attrs:{id:"_5-projections"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-projections"}},[e._v("#")]),e._v(" 5. Projections")]),e._v(" "),a("p",[e._v("Spring Data query methods usually return one or multiple instances of the aggregate root managed by the repository.\nHowever, it might sometimes be desirable to create projections based on certain attributes of those types.\nSpring Data allows modeling dedicated return types, to more selectively retrieve partial views of the managed aggregates.")]),e._v(" "),a("p",[e._v("Imagine a repository and aggregate root type such as the following example:")]),e._v(" "),a("p",[e._v("Example 56. A sample aggregate and repository")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class Person {\n\n  @Id UUID id;\n  String firstname, lastname;\n  Address address;\n\n  static class Address {\n    String zipCode, city, street;\n  }\n}\n\ninterface PersonRepository extends Repository<Person, UUID> {\n\n  Collection<Person> findByLastname(String lastname);\n}\n")])])]),a("p",[e._v("Now imagine that we want to retrieve the person’s name attributes only.\nWhat means does Spring Data offer to achieve this? The rest of this chapter answers that question.")]),e._v(" "),a("h3",{attrs:{id:"_5-1-interface-based-projections"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-1-interface-based-projections"}},[e._v("#")]),e._v(" 5.1. Interface-based Projections")]),e._v(" "),a("p",[e._v("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:")]),e._v(" "),a("p",[e._v("Example 57. A projection interface to retrieve a subset of attributes")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface NamesOnly {\n\n  String getFirstname();\n  String getLastname();\n}\n")])])]),a("p",[e._v("The important bit here is that the properties defined here exactly match properties in the aggregate root.\nDoing so lets a query method be added as follows:")]),e._v(" "),a("p",[e._v("Example 58. A repository using an interface based projection with a query method")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonRepository extends Repository<Person, UUID> {\n\n  Collection<NamesOnly> findByLastname(String lastname);\n}\n")])])]),a("p",[e._v("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.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Declaring a method in your "),a("code",[e._v("Repository")]),e._v(" that overrides a base method (e.g. declared in "),a("code",[e._v("CrudRepository")]),e._v(", a store-specific repository interface, or the "),a("code",[e._v("Simple…Repository")]),e._v(") 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 "),a("code",[e._v("@Query")]),e._v(" annotations to turn an overridden base method into a query method that then can be used to return projections.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Projections can be used recursively. If you want to include some of the "),a("code",[e._v("Address")]),e._v(" information as well, create a projection interface for that and return that interface from the declaration of "),a("code",[e._v("getAddress()")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 59. A projection interface to retrieve a subset of attributes")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonSummary {\n\n  String getFirstname();\n  String getLastname();\n  AddressSummary getAddress();\n\n  interface AddressSummary {\n    String getCity();\n  }\n}\n")])])]),a("p",[e._v("On method invocation, the "),a("code",[e._v("address")]),e._v(" property of the target instance is obtained and wrapped into a projecting proxy in turn.")]),e._v(" "),a("h4",{attrs:{id:"_5-1-1-closed-projections"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-1-1-closed-projections"}},[e._v("#")]),e._v(" 5.1.1. Closed Projections")]),e._v(" "),a("p",[e._v("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:")]),e._v(" "),a("p",[e._v("Example 60. A closed projection")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface NamesOnly {\n\n  String getFirstname();\n  String getLastname();\n}\n")])])]),a("p",[e._v("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.\nFor more details on that, see the module-specific part of the reference documentation.")]),e._v(" "),a("h4",{attrs:{id:"_5-1-2-open-projections"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-1-2-open-projections"}},[e._v("#")]),e._v(" 5.1.2. Open Projections")]),e._v(" "),a("p",[e._v("Accessor methods in projection interfaces can also be used to compute new values by using the "),a("code",[e._v("@Value")]),e._v(" annotation, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 61. An Open Projection")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface NamesOnly {\n\n  @Value(\"#{target.firstname + ' ' + target.lastname}\")\n  String getFullName();\n\n}\n")])])]),a("p",[e._v("The aggregate root backing the projection is available in the "),a("code",[e._v("target")]),e._v(" variable.\nA projection interface using "),a("code",[e._v("@Value")]),e._v(" is an open projection.\nSpring Data cannot apply query execution optimizations in this case, because the SpEL expression could use any attribute of the aggregate root.")]),e._v(" "),a("p",[e._v("The expressions used in "),a("code",[e._v("@Value")]),e._v(" should not be too complex — you want to avoid programming in "),a("code",[e._v("String")]),e._v(" variables.\nFor very simple expressions, one option might be to resort to default methods (introduced in Java 8), as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 62. A projection interface using a default method for custom logic")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('interface NamesOnly {\n\n  String getFirstname();\n  String getLastname();\n\n  default String getFullName() {\n    return getFirstname().concat(" ").concat(getLastname());\n  }\n}\n')])])]),a("p",[e._v("This approach requires you to be able to implement logic purely based on the other accessor methods exposed on the projection interface.\nA 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:")]),e._v(" "),a("p",[e._v("Example 63. Sample Person object")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Component\nclass MyBean {\n\n  String getFullName(Person person) {\n\n  }\n}\n\ninterface NamesOnly {\n\n  @Value("#{@myBean.getFullName(target)}")\n  String getFullName();\n\n}\n')])])]),a("p",[e._v("Notice how the SpEL expression refers to "),a("code",[e._v("myBean")]),e._v(" and invokes the "),a("code",[e._v("getFullName(…)")]),e._v(" method and forwards the projection target as a method parameter.\nMethods backed by SpEL expression evaluation can also use method parameters, which can then be referred to from the expression.\nThe method parameters are available through an "),a("code",[e._v("Object")]),e._v(" array named "),a("code",[e._v("args")]),e._v(". The following example shows how to get a method parameter from the "),a("code",[e._v("args")]),e._v(" array:")]),e._v(" "),a("p",[e._v("Example 64. Sample Person object")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface NamesOnly {\n\n  @Value(\"#{args[0] + ' ' + target.firstname + '!'}\")\n  String getSalutation(String prefix);\n}\n")])])]),a("p",[e._v("Again, for more complex expressions, you should use a Spring bean and let the expression invoke a method, as described "),a("a",{attrs:{href:"#projections.interfaces.open.bean-reference"}},[e._v("earlier")]),e._v(".")]),e._v(" "),a("h4",{attrs:{id:"_5-1-3-nullable-wrappers"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-1-3-nullable-wrappers"}},[e._v("#")]),e._v(" 5.1.3. Nullable Wrappers")]),e._v(" "),a("p",[e._v("Getters in projection interfaces can make use of nullable wrappers for improved null-safety. Currently supported wrapper types are:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("java.util.Optional")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("com.google.common.base.Optional")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("scala.Option")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("io.vavr.control.Option")])])])]),e._v(" "),a("p",[e._v("Example 65. A projection interface using nullable wrappers")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface NamesOnly {\n\n  Optional<String> getFirstname();\n}\n")])])]),a("p",[e._v("If the underlying projection value is not "),a("code",[e._v("null")]),e._v(", then values are returned using the present-representation of the wrapper type.\nIn case the backing value is "),a("code",[e._v("null")]),e._v(", then the getter method returns the empty representation of the used wrapper type.")]),e._v(" "),a("h3",{attrs:{id:"_5-2-class-based-projections-dtos"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-2-class-based-projections-dtos"}},[e._v("#")]),e._v(" 5.2. Class-based Projections (DTOs)")]),e._v(" "),a("p",[e._v("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.\nThese 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.")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("p",[e._v("The following example shows a projecting DTO:")]),e._v(" "),a("p",[e._v("Example 66. A projecting DTO")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class NamesOnly {\n\n  private final String firstname, lastname;\n\n  NamesOnly(String firstname, String lastname) {\n\n    this.firstname = firstname;\n    this.lastname = lastname;\n  }\n\n  String getFirstname() {\n    return this.firstname;\n  }\n\n  String getLastname() {\n    return this.lastname;\n  }\n\n  // equals(…) and hashCode() implementations\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Avoid boilerplate code for projection DTOs"),a("br"),a("br"),e._v("You can dramatically simplify the code for a DTO by using "),a("a",{attrs:{href:"https://projectlombok.org",target:"_blank",rel:"noopener noreferrer"}},[e._v("Project Lombok"),a("OutboundLink")],1),e._v(", which provides an "),a("code",[e._v("@Value")]),e._v(" annotation (not to be confused with Spring’s "),a("code",[e._v("@Value")]),e._v(" annotation shown in the earlier interface examples)."),a("br"),e._v("If you use Project Lombok’s "),a("code",[e._v("@Value")]),e._v(" annotation, the sample DTO shown earlier would become the following:"),a("br"),a("br"),a("code",[e._v("<br/>@Value<br/>class NamesOnly {<br/>\tString firstname, lastname;<br/>}<br/>")]),a("br"),a("br"),e._v("Fields are "),a("code",[e._v("private final")]),e._v(" by default, and the class exposes a constructor that takes all fields and automatically gets "),a("code",[e._v("equals(…)")]),e._v(" and "),a("code",[e._v("hashCode()")]),e._v(" methods implemented.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_5-3-dynamic-projections"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-3-dynamic-projections"}},[e._v("#")]),e._v(" 5.3. Dynamic Projections")]),e._v(" "),a("p",[e._v("So far, we have used the projection type as the return type or element type of a collection.\nHowever, you might want to select the type to be used at invocation time (which makes it dynamic).\nTo apply dynamic projections, use a query method such as the one shown in the following example:")]),e._v(" "),a("p",[e._v("Example 67. A repository using a dynamic projection parameter")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("interface PersonRepository extends Repository<Person, UUID> {\n\n  <T> Collection<T> findByLastname(String lastname, Class<T> type);\n}\n")])])]),a("p",[e._v("This way, the method can be used to obtain the aggregates as is or with a projection applied, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 68. Using a repository with dynamic projections")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('void someMethod(PersonRepository people) {\n\n  Collection<Person> aggregates =\n    people.findByLastname("Matthews", Person.class);\n\n  Collection<NamesOnly> aggregates =\n    people.findByLastname("Matthews", NamesOnly.class);\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Query parameters of type "),a("code",[e._v("Class")]),e._v(" are inspected whether they qualify as dynamic projection parameter."),a("br"),e._v("If the actual return type of the query equals the generic parameter type of the "),a("code",[e._v("Class")]),e._v(" parameter, then the matching "),a("code",[e._v("Class")]),e._v(" parameter is not available for usage within the query or SpEL expressions."),a("br"),e._v("If you want to use a "),a("code",[e._v("Class")]),e._v(" parameter as query argument then make sure to use a different generic parameter, for example "),a("code",[e._v("Class<?>")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h2",{attrs:{id:"_6-query-by-example"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-query-by-example"}},[e._v("#")]),e._v(" 6. Query by Example")]),e._v(" "),a("h3",{attrs:{id:"_6-1-introduction"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-1-introduction"}},[e._v("#")]),e._v(" 6.1. Introduction")]),e._v(" "),a("p",[e._v("This chapter provides an introduction to Query by Example and explains how to use it.")]),e._v(" "),a("p",[e._v("Query by Example (QBE) is a user-friendly querying technique with a simple interface.\nIt allows dynamic query creation and does not require you to write queries that contain field names.\nIn fact, Query by Example does not require you to write queries by using store-specific query languages at all.")]),e._v(" "),a("h3",{attrs:{id:"_6-2-usage"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-2-usage"}},[e._v("#")]),e._v(" 6.2. Usage")]),e._v(" "),a("p",[e._v("The Query by Example API consists of three parts:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Probe: The actual example of a domain object with populated fields.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("ExampleMatcher")]),e._v(": The "),a("code",[e._v("ExampleMatcher")]),e._v(" carries details on how to match particular fields.\nIt can be reused across multiple Examples.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("Example")]),e._v(": An "),a("code",[e._v("Example")]),e._v(" consists of the probe and the "),a("code",[e._v("ExampleMatcher")]),e._v(".\nIt is used to create the query.")])])]),e._v(" "),a("p",[e._v("Query by Example is well suited for several use cases:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Querying your data store with a set of static or dynamic constraints.")])]),e._v(" "),a("li",[a("p",[e._v("Frequent refactoring of the domain objects without worrying about breaking existing queries.")])]),e._v(" "),a("li",[a("p",[e._v("Working independently from the underlying data store API.")])])]),e._v(" "),a("p",[e._v("Query by Example also has several limitations:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("No support for nested or grouped property constraints, such as "),a("code",[e._v("firstname = ?0 or (firstname = ?1 and lastname = ?2)")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.")])])]),e._v(" "),a("p",[e._v("Before getting started with Query by Example, you need to have a domain object.\nTo get started, create an interface for your repository, as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 69. Sample Person object")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public class Person {\n\n  @Id\n  private String id;\n  private String firstname;\n  private String lastname;\n  private Address address;\n\n  // … getters and setters omitted\n}\n")])])]),a("p",[e._v("The preceding example shows a simple domain object.\nYou can use it to create an "),a("code",[e._v("Example")]),e._v(".\nBy default, fields having "),a("code",[e._v("null")]),e._v(" values are ignored, and strings are matched by using the store specific defaults.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Inclusion of properties into a Query by Example criteria is based on nullability. Properties using primitive types ("),a("code",[e._v("int")]),e._v(", "),a("code",[e._v("double")]),e._v(", …) are always included unless "),a("a",{attrs:{href:"#query-by-example.matchers"}},[e._v("ignoring the property path")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Examples can be built by either using the "),a("code",[e._v("of")]),e._v(" factory method or by using "),a("a",{attrs:{href:"#query-by-example.matchers"}},[a("code",[e._v("ExampleMatcher")])]),e._v(". "),a("code",[e._v("Example")]),e._v(" is immutable.\nThe following listing shows a simple Example:")]),e._v(" "),a("p",[e._v("Example 70. Simple Example")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('Person person = new Person();                         (1)\nperson.setFirstname("Dave");                          (2)\n\nExample<Person> example = Example.of(person);         (3)\n')])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("Create a new instance of the domain object.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("Set the properties to query.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Create the "),a("code",[e._v("Example")]),e._v(".")])])])]),e._v(" "),a("p",[e._v("You can run the example queries by using repositories.\nTo do so, let your repository interface extend "),a("code",[e._v("QueryByExampleExecutor<T>")]),e._v(".\nThe following listing shows an excerpt from the "),a("code",[e._v("QueryByExampleExecutor")]),e._v(" interface:")]),e._v(" "),a("p",[e._v("Example 71. The "),a("code",[e._v("QueryByExampleExecutor")])]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public interface QueryByExampleExecutor<T> {\n\n  <S extends T> S findOne(Example<S> example);\n\n  <S extends T> Iterable<S> findAll(Example<S> example);\n\n  // … more functionality omitted.\n}\n")])])]),a("h3",{attrs:{id:"_6-3-example-matchers"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-3-example-matchers"}},[e._v("#")]),e._v(" 6.3. Example Matchers")]),e._v(" "),a("p",[e._v("Examples are not limited to default settings.\nYou can specify your own defaults for string matching, null handling, and property-specific settings by using the "),a("code",[e._v("ExampleMatcher")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Example 72. Example matcher with customized matching")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('Person person = new Person();                          (1)\nperson.setFirstname("Dave");                           (2)\n\nExampleMatcher matcher = ExampleMatcher.matching()     (3)\n  .withIgnorePaths("lastname")                         (4)\n  .withIncludeNullValues()                             (5)\n  .withStringMatcher(StringMatcher.ENDING);            (6)\n\nExample<Person> example = Example.of(person, matcher); (7)\n')])])]),a("table",[a("thead",[a("tr",[a("th",[a("strong",[e._v("1")])]),e._v(" "),a("th",[e._v("Create a new instance of the domain object.")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("strong",[e._v("2")])]),e._v(" "),a("td",[e._v("Set properties.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("3")])]),e._v(" "),a("td",[e._v("Create an "),a("code",[e._v("ExampleMatcher")]),e._v(" to expect all values to match."),a("br"),e._v("It is usable at this stage even without further configuration.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("4")])]),e._v(" "),a("td",[e._v("Construct a new "),a("code",[e._v("ExampleMatcher")]),e._v(" to ignore the "),a("code",[e._v("lastname")]),e._v(" property path.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("5")])]),e._v(" "),a("td",[e._v("Construct a new "),a("code",[e._v("ExampleMatcher")]),e._v(" to ignore the "),a("code",[e._v("lastname")]),e._v(" property path and to include null values.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("6")])]),e._v(" "),a("td",[e._v("Construct a new "),a("code",[e._v("ExampleMatcher")]),e._v(" to ignore the "),a("code",[e._v("lastname")]),e._v(" property path, to include null values, and to perform suffix string matching.")])]),e._v(" "),a("tr",[a("td",[a("strong",[e._v("7")])]),e._v(" "),a("td",[e._v("Create a new "),a("code",[e._v("Example")]),e._v(" based on the domain object and the configured "),a("code",[e._v("ExampleMatcher")]),e._v(".")])])])]),e._v(" "),a("p",[e._v("By default, the "),a("code",[e._v("ExampleMatcher")]),e._v(" expects all values set on the probe to match.\nIf you want to get results matching any of the predicates defined implicitly, use "),a("code",[e._v("ExampleMatcher.matchingAny()")]),e._v(".")]),e._v(" "),a("p",[e._v('You can specify behavior for individual properties (such as "firstname" and "lastname" or, for nested properties, "address.city").\nYou can tune it with matching options and case sensitivity, as shown in the following example:')]),e._v(" "),a("p",[e._v("Example 73. Configuring matcher options")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('ExampleMatcher matcher = ExampleMatcher.matching()\n  .withMatcher("firstname", endsWith())\n  .withMatcher("lastname", startsWith().ignoreCase());\n}\n')])])]),a("p",[e._v("Another way to configure matcher options is to use lambdas (introduced in Java 8).\nThis approach creates a callback that asks the implementor to modify the matcher.\nYou need not return the matcher, because configuration options are held within the matcher instance.\nThe following example shows a matcher that uses lambdas:")]),e._v(" "),a("p",[e._v("Example 74. Configuring matcher options with lambdas")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('ExampleMatcher matcher = ExampleMatcher.matching()\n  .withMatcher("firstname", match -> match.endsWith())\n  .withMatcher("firstname", match -> match.startsWith());\n}\n')])])]),a("p",[e._v("Queries created by "),a("code",[e._v("Example")]),e._v(" use a merged view of the configuration.\nDefault matching settings can be set at the "),a("code",[e._v("ExampleMatcher")]),e._v(" level, while individual settings can be applied to particular property paths.\nSettings that are set on "),a("code",[e._v("ExampleMatcher")]),e._v(" are inherited by property path settings unless they are defined explicitly.\nSettings on a property patch have higher precedence than default settings.\nThe following table describes the scope of the various "),a("code",[e._v("ExampleMatcher")]),e._v(" settings:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Setting")]),e._v(" "),a("th",[e._v("Scope")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[e._v("Null-handling")]),e._v(" "),a("td",[a("code",[e._v("ExampleMatcher")])])]),e._v(" "),a("tr",[a("td",[e._v("String matching")]),e._v(" "),a("td",[a("code",[e._v("ExampleMatcher")]),e._v(" and property path")])]),e._v(" "),a("tr",[a("td",[e._v("Ignoring properties")]),e._v(" "),a("td",[e._v("Property path")])]),e._v(" "),a("tr",[a("td",[e._v("Case sensitivity")]),e._v(" "),a("td",[a("code",[e._v("ExampleMatcher")]),e._v(" and property path")])]),e._v(" "),a("tr",[a("td",[e._v("Value transformation")]),e._v(" "),a("td",[e._v("Property path")])])])]),e._v(" "),a("h2",{attrs:{id:"_7-auditing"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-auditing"}},[e._v("#")]),e._v(" 7. Auditing")]),e._v(" "),a("h3",{attrs:{id:"_7-1-basics"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-basics"}},[e._v("#")]),e._v(" 7.1. Basics")]),e._v(" "),a("p",[e._v("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.\nAdditionally, auditing has to be enabled either through Annotation configuration or XML configuration to register the required infrastructure components.\nPlease refer to the store-specific section for configuration samples.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Applications that only track creation and modification dates do not need to specify an "),a("a",{attrs:{href:"#auditing.auditor-aware"}},[a("code",[e._v("AuditorAware")])]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_7-1-1-annotation-based-auditing-metadata"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-1-annotation-based-auditing-metadata"}},[e._v("#")]),e._v(" 7.1.1. Annotation-based Auditing Metadata")]),e._v(" "),a("p",[e._v("We provide "),a("code",[e._v("@CreatedBy")]),e._v(" and "),a("code",[e._v("@LastModifiedBy")]),e._v(" to capture the user who created or modified the entity as well as "),a("code",[e._v("@CreatedDate")]),e._v(" and "),a("code",[e._v("@LastModifiedDate")]),e._v(" to capture when the change happened.")]),e._v(" "),a("p",[e._v("Example 75. An audited entity")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class Customer {\n\n  @CreatedBy\n  private User user;\n\n  @CreatedDate\n  private Instant createdDate;\n\n  // … further properties omitted\n}\n")])])]),a("p",[e._v("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, "),a("code",[e._v("DateTime")]),e._v(", legacy Java "),a("code",[e._v("Date")]),e._v(" and "),a("code",[e._v("Calendar")]),e._v(", JDK8 date and time types, and "),a("code",[e._v("long")]),e._v(" or "),a("code",[e._v("Long")]),e._v(".")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("p",[e._v("Example 76. Audit metadata in embedded entity")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class Customer {\n\n  private AuditMetadata auditingMetadata;\n\n  // … further properties omitted\n}\n\nclass AuditMetadata {\n\n  @CreatedBy\n  private User user;\n\n  @CreatedDate\n  private Instant createdDate;\n\n}\n")])])]),a("h4",{attrs:{id:"_7-1-2-interface-based-auditing-metadata"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-2-interface-based-auditing-metadata"}},[e._v("#")]),e._v(" 7.1.2. Interface-based Auditing Metadata")]),e._v(" "),a("p",[e._v("In case you do not want to use annotations to define auditing metadata, you can let your domain class implement the "),a("code",[e._v("Auditable")]),e._v(" interface. It exposes setter methods for all of the auditing properties.")]),e._v(" "),a("h4",{attrs:{id:"_7-1-3-auditoraware"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-3-auditoraware"}},[e._v("#")]),e._v(" 7.1.3. "),a("code",[e._v("AuditorAware")])]),e._v(" "),a("p",[e._v("In case you use either "),a("code",[e._v("@CreatedBy")]),e._v(" or "),a("code",[e._v("@LastModifiedBy")]),e._v(", the auditing infrastructure somehow needs to become aware of the current principal. To do so, we provide an "),a("code",[e._v("AuditorAware<T>")]),e._v(" 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 "),a("code",[e._v("T")]),e._v(" defines what type the properties annotated with "),a("code",[e._v("@CreatedBy")]),e._v(" or "),a("code",[e._v("@LastModifiedBy")]),e._v(" have to be.")]),e._v(" "),a("p",[e._v("The following example shows an implementation of the interface that uses Spring Security’s "),a("code",[e._v("Authentication")]),e._v(" object:")]),e._v(" "),a("p",[e._v("Example 77. Implementation of "),a("code",[e._v("AuditorAware")]),e._v(" based on Spring Security")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class SpringSecurityAuditorAware implements AuditorAware<User> {\n\n  @Override\n  public Optional<User> getCurrentAuditor() {\n\n    return Optional.ofNullable(SecurityContextHolder.getContext())\n            .map(SecurityContext::getAuthentication)\n            .filter(Authentication::isAuthenticated)\n            .map(Authentication::getPrincipal)\n            .map(User.class::cast);\n  }\n}\n")])])]),a("p",[e._v("The implementation accesses the "),a("code",[e._v("Authentication")]),e._v(" object provided by Spring Security and looks up the custom "),a("code",[e._v("UserDetails")]),e._v(" instance that you have created in your "),a("code",[e._v("UserDetailsService")]),e._v(" implementation. We assume here that you are exposing the domain user through the "),a("code",[e._v("UserDetails")]),e._v(" implementation but that, based on the "),a("code",[e._v("Authentication")]),e._v(" found, you could also look it up from anywhere.")]),e._v(" "),a("h4",{attrs:{id:"_7-1-4-reactiveauditoraware"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-4-reactiveauditoraware"}},[e._v("#")]),e._v(" 7.1.4. "),a("code",[e._v("ReactiveAuditorAware")])]),e._v(" "),a("p",[e._v("When using reactive infrastructure you might want to make use of contextual information to provide "),a("code",[e._v("@CreatedBy")]),e._v(" or "),a("code",[e._v("@LastModifiedBy")]),e._v(" information.\nWe provide an "),a("code",[e._v("ReactiveAuditorAware<T>")]),e._v(" 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 "),a("code",[e._v("T")]),e._v(" defines what type the properties annotated with "),a("code",[e._v("@CreatedBy")]),e._v(" or "),a("code",[e._v("@LastModifiedBy")]),e._v(" have to be.")]),e._v(" "),a("p",[e._v("The following example shows an implementation of the interface that uses reactive Spring Security’s "),a("code",[e._v("Authentication")]),e._v(" object:")]),e._v(" "),a("p",[e._v("Example 78. Implementation of "),a("code",[e._v("ReactiveAuditorAware")]),e._v(" based on Spring Security")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class SpringSecurityAuditorAware implements ReactiveAuditorAware<User> {\n\n  @Override\n  public Mono<User> getCurrentAuditor() {\n\n    return ReactiveSecurityContextHolder.getContext()\n                .map(SecurityContext::getAuthentication)\n                .filter(Authentication::isAuthenticated)\n                .map(Authentication::getPrincipal)\n                .map(User.class::cast);\n  }\n}\n")])])]),a("p",[e._v("The implementation accesses the "),a("code",[e._v("Authentication")]),e._v(" object provided by Spring Security and looks up the custom "),a("code",[e._v("UserDetails")]),e._v(" instance that you have created in your "),a("code",[e._v("UserDetailsService")]),e._v(" implementation. We assume here that you are exposing the domain user through the "),a("code",[e._v("UserDetails")]),e._v(" implementation but that, based on the "),a("code",[e._v("Authentication")]),e._v(" found, you could also look it up from anywhere.")]),e._v(" "),a("h2",{attrs:{id:"appendices"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#appendices"}},[e._v("#")]),e._v(" Appendices")]),e._v(" "),a("h2",{attrs:{id:"appendix-a-namespace-reference"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#appendix-a-namespace-reference"}},[e._v("#")]),e._v(" Appendix A: Namespace reference")]),e._v(" "),a("h3",{attrs:{id:"the-repositories-element"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#the-repositories-element"}},[e._v("#")]),e._v(" The "),a("code",[e._v("<repositories />")]),e._v(" Element")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("<repositories />")]),e._v(" element triggers the setup of the Spring Data repository infrastructure. The most important attribute is "),a("code",[e._v("base-package")]),e._v(", which defines the package to scan for Spring Data repository interfaces. See “"),a("a",{attrs:{href:"#repositories.create-instances.spring"}},[e._v("XML Configuration")]),e._v("”. The following table describes the attributes of the "),a("code",[e._v("<repositories />")]),e._v(" element:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Name")]),e._v(" "),a("th",[e._v("Description")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("base-package")])]),e._v(" "),a("td",[e._v("Defines the package to be scanned for repository interfaces that extend "),a("code",[e._v("*Repository")]),e._v(" (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.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("repository-impl-postfix")])]),e._v(" "),a("td",[e._v("Defines the postfix to autodetect custom repository implementations. Classes whose names end with the configured postfix are considered as candidates. Defaults to "),a("code",[e._v("Impl")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("query-lookup-strategy")])]),e._v(" "),a("td",[e._v("Determines the strategy to be used to create finder queries. See “"),a("a",{attrs:{href:"#repositories.query-methods.query-lookup-strategies"}},[e._v("Query Lookup Strategies")]),e._v("” for details. Defaults to "),a("code",[e._v("create-if-not-found")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("named-queries-location")])]),e._v(" "),a("td",[e._v("Defines the location to search for a Properties file containing externally defined queries.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("consider-nested-repositories")])]),e._v(" "),a("td",[e._v("Whether nested repository interface definitions should be considered. Defaults to "),a("code",[e._v("false")]),e._v(".")])])])]),e._v(" "),a("h2",{attrs:{id:"appendix-b-populators-namespace-reference"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#appendix-b-populators-namespace-reference"}},[e._v("#")]),e._v(" Appendix B: Populators namespace reference")]),e._v(" "),a("h3",{attrs:{id:"the-populator-element"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#the-populator-element"}},[e._v("#")]),e._v(" The <populator /> element")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("<populator />")]),e._v(" element allows to populate the a data store via the Spring Data repository infrastructure."),a("sup",{staticClass:"footnote"},[e._v("["),a("a",{staticClass:"footnote",attrs:{id:"_footnoteref_1",href:"#_footnotedef_1",title:"View footnote."}},[e._v("1")]),e._v("]")])]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Name")]),e._v(" "),a("th",[e._v("Description")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("locations")])]),e._v(" "),a("td",[e._v("Where to find the files to read the objects from the repository shall be populated with.")])])])]),e._v(" "),a("h2",{attrs:{id:"appendix-c-repository-query-keywords"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#appendix-c-repository-query-keywords"}},[e._v("#")]),e._v(" Appendix C: Repository query keywords")]),e._v(" "),a("h3",{attrs:{id:"supported-query-method-subject-keywords"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#supported-query-method-subject-keywords"}},[e._v("#")]),e._v(" Supported query method subject keywords")]),e._v(" "),a("p",[e._v("The following table lists the subject keywords generally supported by the Spring Data repository query derivation mechanism to express the predicate.\nConsult the store-specific documentation for the exact list of supported keywords, because some keywords listed here might not be supported in a particular store.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Keyword")]),e._v(" "),a("th",[e._v("Description")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("find…By")]),e._v(", "),a("code",[e._v("read…By")]),e._v(", "),a("code",[e._v("get…By")]),e._v(", "),a("code",[e._v("query…By")]),e._v(", "),a("code",[e._v("search…By")]),e._v(", "),a("code",[e._v("stream…By")])]),e._v(" "),a("td",[e._v("General query method returning typically the repository type, a "),a("code",[e._v("Collection")]),e._v(" or "),a("code",[e._v("Streamable")]),e._v(" subtype or a result wrapper such as "),a("code",[e._v("Page")]),e._v(", "),a("code",[e._v("GeoResults")]),e._v(" or any other store-specific result wrapper. Can be used as "),a("code",[e._v("findBy…")]),e._v(", "),a("code",[e._v("findMyDomainTypeBy…")]),e._v(" or in combination with additional keywords.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("exists…By")])]),e._v(" "),a("td",[e._v("Exists projection, returning typically a "),a("code",[e._v("boolean")]),e._v(" result.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("count…By")])]),e._v(" "),a("td",[e._v("Count projection returning a numeric result.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("delete…By")]),e._v(", "),a("code",[e._v("remove…By")])]),e._v(" "),a("td",[e._v("Delete query method returning either no result ("),a("code",[e._v("void")]),e._v(") or the delete count.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("…First<number>…")]),e._v(", "),a("code",[e._v("…Top<number>…")])]),e._v(" "),a("td",[e._v("Limit the query results to the first "),a("code",[e._v("<number>")]),e._v(" of results. This keyword can occur in any place of the subject between "),a("code",[e._v("find")]),e._v(" (and the other keywords) and "),a("code",[e._v("by")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("…Distinct…")])]),e._v(" "),a("td",[e._v("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 "),a("code",[e._v("find")]),e._v(" (and the other keywords) and "),a("code",[e._v("by")]),e._v(".")])])])]),e._v(" "),a("h3",{attrs:{id:"supported-query-method-predicate-keywords-and-modifiers"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#supported-query-method-predicate-keywords-and-modifiers"}},[e._v("#")]),e._v(" Supported query method predicate keywords and modifiers")]),e._v(" "),a("p",[e._v("The following table lists the predicate keywords generally supported by the Spring Data repository query derivation mechanism.\nHowever, 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.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Logical keyword")]),e._v(" "),a("th",[e._v("Keyword expressions")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("AND")])]),e._v(" "),a("td",[a("code",[e._v("And")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("OR")])]),e._v(" "),a("td",[a("code",[e._v("Or")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("AFTER")])]),e._v(" "),a("td",[a("code",[e._v("After")]),e._v(", "),a("code",[e._v("IsAfter")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("BEFORE")])]),e._v(" "),a("td",[a("code",[e._v("Before")]),e._v(", "),a("code",[e._v("IsBefore")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("CONTAINING")])]),e._v(" "),a("td",[a("code",[e._v("Containing")]),e._v(", "),a("code",[e._v("IsContaining")]),e._v(", "),a("code",[e._v("Contains")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("BETWEEN")])]),e._v(" "),a("td",[a("code",[e._v("Between")]),e._v(", "),a("code",[e._v("IsBetween")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("ENDING_WITH")])]),e._v(" "),a("td",[a("code",[e._v("EndingWith")]),e._v(", "),a("code",[e._v("IsEndingWith")]),e._v(", "),a("code",[e._v("EndsWith")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("EXISTS")])]),e._v(" "),a("td",[a("code",[e._v("Exists")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("FALSE")])]),e._v(" "),a("td",[a("code",[e._v("False")]),e._v(", "),a("code",[e._v("IsFalse")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("GREATER_THAN")])]),e._v(" "),a("td",[a("code",[e._v("GreaterThan")]),e._v(", "),a("code",[e._v("IsGreaterThan")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("GREATER_THAN_EQUALS")])]),e._v(" "),a("td",[a("code",[e._v("GreaterThanEqual")]),e._v(", "),a("code",[e._v("IsGreaterThanEqual")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("IN")])]),e._v(" "),a("td",[a("code",[e._v("In")]),e._v(", "),a("code",[e._v("IsIn")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("IS")])]),e._v(" "),a("td",[a("code",[e._v("Is")]),e._v(", "),a("code",[e._v("Equals")]),e._v(", (or no keyword)")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("IS_EMPTY")])]),e._v(" "),a("td",[a("code",[e._v("IsEmpty")]),e._v(", "),a("code",[e._v("Empty")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("IS_NOT_EMPTY")])]),e._v(" "),a("td",[a("code",[e._v("IsNotEmpty")]),e._v(", "),a("code",[e._v("NotEmpty")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("IS_NOT_NULL")])]),e._v(" "),a("td",[a("code",[e._v("NotNull")]),e._v(", "),a("code",[e._v("IsNotNull")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("IS_NULL")])]),e._v(" "),a("td",[a("code",[e._v("Null")]),e._v(", "),a("code",[e._v("IsNull")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("LESS_THAN")])]),e._v(" "),a("td",[a("code",[e._v("LessThan")]),e._v(", "),a("code",[e._v("IsLessThan")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("LESS_THAN_EQUAL")])]),e._v(" "),a("td",[a("code",[e._v("LessThanEqual")]),e._v(", "),a("code",[e._v("IsLessThanEqual")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("LIKE")])]),e._v(" "),a("td",[a("code",[e._v("Like")]),e._v(", "),a("code",[e._v("IsLike")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("NEAR")])]),e._v(" "),a("td",[a("code",[e._v("Near")]),e._v(", "),a("code",[e._v("IsNear")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("NOT")])]),e._v(" "),a("td",[a("code",[e._v("Not")]),e._v(", "),a("code",[e._v("IsNot")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("NOT_IN")])]),e._v(" "),a("td",[a("code",[e._v("NotIn")]),e._v(", "),a("code",[e._v("IsNotIn")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("NOT_LIKE")])]),e._v(" "),a("td",[a("code",[e._v("NotLike")]),e._v(", "),a("code",[e._v("IsNotLike")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("REGEX")])]),e._v(" "),a("td",[a("code",[e._v("Regex")]),e._v(", "),a("code",[e._v("MatchesRegex")]),e._v(", "),a("code",[e._v("Matches")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("STARTING_WITH")])]),e._v(" "),a("td",[a("code",[e._v("StartingWith")]),e._v(", "),a("code",[e._v("IsStartingWith")]),e._v(", "),a("code",[e._v("StartsWith")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("TRUE")])]),e._v(" "),a("td",[a("code",[e._v("True")]),e._v(", "),a("code",[e._v("IsTrue")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("WITHIN")])]),e._v(" "),a("td",[a("code",[e._v("Within")]),e._v(", "),a("code",[e._v("IsWithin")])])])])]),e._v(" "),a("p",[e._v("In addition to filter predicates, the following list of modifiers is supported:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Keyword")]),e._v(" "),a("th",[e._v("Description")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("IgnoreCase")]),e._v(", "),a("code",[e._v("IgnoringCase")])]),e._v(" "),a("td",[e._v("Used with a predicate keyword for case-insensitive comparison.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("AllIgnoreCase")]),e._v(", "),a("code",[e._v("AllIgnoringCase")])]),e._v(" "),a("td",[e._v("Ignore case for all suitable properties. Used somewhere in the query method predicate.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("OrderBy…")])]),e._v(" "),a("td",[e._v("Specify a static sorting order followed by the property path and direction (e. g. "),a("code",[e._v("OrderByFirstnameAscLastnameDesc")]),e._v(").")])])])]),e._v(" "),a("h2",{attrs:{id:"appendix-d-repository-query-return-types"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#appendix-d-repository-query-return-types"}},[e._v("#")]),e._v(" Appendix D: Repository query return types")]),e._v(" "),a("h3",{attrs:{id:"supported-query-return-types"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#supported-query-return-types"}},[e._v("#")]),e._v(" Supported Query Return Types")]),e._v(" "),a("p",[e._v("The following table lists the return types generally supported by Spring Data repositories.\nHowever, 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.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Geospatial types (such as "),a("code",[e._v("GeoResult")]),e._v(", "),a("code",[e._v("GeoResults")]),e._v(", and "),a("code",[e._v("GeoPage")]),e._v(") are available only for data stores that support geospatial queries."),a("br"),e._v("Some store modules may define their own result wrapper types.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Return type")]),e._v(" "),a("th",[e._v("Description")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("void")])]),e._v(" "),a("td",[e._v("Denotes no return value.")])]),e._v(" "),a("tr",[a("td",[e._v("Primitives")]),e._v(" "),a("td",[e._v("Java primitives.")])]),e._v(" "),a("tr",[a("td",[e._v("Wrapper types")]),e._v(" "),a("td",[e._v("Java wrapper types.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("T")])]),e._v(" "),a("td",[e._v("A unique entity. Expects the query method to return one result at most. If no result is found, "),a("code",[e._v("null")]),e._v(" is returned. More than one result triggers an "),a("code",[e._v("IncorrectResultSizeDataAccessException")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Iterator<T>")])]),e._v(" "),a("td",[e._v("An "),a("code",[e._v("Iterator")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Collection<T>")])]),e._v(" "),a("td",[e._v("A "),a("code",[e._v("Collection")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("List<T>")])]),e._v(" "),a("td",[e._v("A "),a("code",[e._v("List")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Optional<T>")])]),e._v(" "),a("td",[e._v("A Java 8 or Guava "),a("code",[e._v("Optional")]),e._v(". Expects the query method to return one result at most. If no result is found, "),a("code",[e._v("Optional.empty()")]),e._v(" or "),a("code",[e._v("Optional.absent()")]),e._v(" is returned. More than one result triggers an "),a("code",[e._v("IncorrectResultSizeDataAccessException")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Option<T>")])]),e._v(" "),a("td",[e._v("Either a Scala or Vavr "),a("code",[e._v("Option")]),e._v(" type. Semantically the same behavior as Java 8’s "),a("code",[e._v("Optional")]),e._v(", described earlier.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Stream<T>")])]),e._v(" "),a("td",[e._v("A Java 8 "),a("code",[e._v("Stream")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Streamable<T>")])]),e._v(" "),a("td",[e._v("A convenience extension of "),a("code",[e._v("Iterable")]),e._v(" that directy exposes methods to stream, map and filter results, concatenate them etc.")])]),e._v(" "),a("tr",[a("td",[e._v("Types that implement "),a("code",[e._v("Streamable")]),e._v(" and take a "),a("code",[e._v("Streamable")]),e._v(" constructor or factory method argument")]),e._v(" "),a("td",[e._v("Types that expose a constructor or "),a("code",[e._v("….of(…)")]),e._v("/"),a("code",[e._v("….valueOf(…)")]),e._v(" factory method taking a "),a("code",[e._v("Streamable")]),e._v(" as argument. See "),a("a",{attrs:{href:"#repositories.collections-and-iterables.streamable-wrapper"}},[e._v("Returning Custom Streamable Wrapper Types")]),e._v(" for details.")])]),e._v(" "),a("tr",[a("td",[e._v("Vavr "),a("code",[e._v("Seq")]),e._v(", "),a("code",[e._v("List")]),e._v(", "),a("code",[e._v("Map")]),e._v(", "),a("code",[e._v("Set")])]),e._v(" "),a("td",[e._v("Vavr collection types. See "),a("a",{attrs:{href:"#repositories.collections-and-iterables.vavr"}},[e._v("Support for Vavr Collections")]),e._v(" for details.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Future<T>")])]),e._v(" "),a("td",[e._v("A "),a("code",[e._v("Future")]),e._v(". Expects a method to be annotated with "),a("code",[e._v("@Async")]),e._v(" and requires Spring’s asynchronous method execution capability to be enabled.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("CompletableFuture<T>")])]),e._v(" "),a("td",[e._v("A Java 8 "),a("code",[e._v("CompletableFuture")]),e._v(". Expects a method to be annotated with "),a("code",[e._v("@Async")]),e._v(" and requires Spring’s asynchronous method execution capability to be enabled.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("ListenableFuture")])]),e._v(" "),a("td",[e._v("A "),a("code",[e._v("org.springframework.util.concurrent.ListenableFuture")]),e._v(". Expects a method to be annotated with "),a("code",[e._v("@Async")]),e._v(" and requires Spring’s asynchronous method execution capability to be enabled.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Slice<T>")])]),e._v(" "),a("td",[e._v("A sized chunk of data with an indication of whether there is more data available. Requires a "),a("code",[e._v("Pageable")]),e._v(" method parameter.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Page<T>")])]),e._v(" "),a("td",[e._v("A "),a("code",[e._v("Slice")]),e._v(" with additional information, such as the total number of results. Requires a "),a("code",[e._v("Pageable")]),e._v(" method parameter.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("GeoResult<T>")])]),e._v(" "),a("td",[e._v("A result entry with additional information, such as the distance to a reference location.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("GeoResults<T>")])]),e._v(" "),a("td",[e._v("A list of "),a("code",[e._v("GeoResult<T>")]),e._v(" with additional information, such as the average distance to a reference location.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("GeoPage<T>")])]),e._v(" "),a("td",[e._v("A "),a("code",[e._v("Page")]),e._v(" with "),a("code",[e._v("GeoResult<T>")]),e._v(", such as the average distance to a reference location.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Mono<T>")])]),e._v(" "),a("td",[e._v("A Project Reactor "),a("code",[e._v("Mono")]),e._v(" emitting zero or one element using reactive repositories. Expects the query method to return one result at most. If no result is found, "),a("code",[e._v("Mono.empty()")]),e._v(" is returned. More than one result triggers an "),a("code",[e._v("IncorrectResultSizeDataAccessException")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Flux<T>")])]),e._v(" "),a("td",[e._v("A Project Reactor "),a("code",[e._v("Flux")]),e._v(" emitting zero, one, or many elements using reactive repositories. Queries returning "),a("code",[e._v("Flux")]),e._v(" can emit also an infinite number of elements.")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Single<T>")])]),e._v(" "),a("td",[e._v("A RxJava "),a("code",[e._v("Single")]),e._v(" emitting a single element using reactive repositories. Expects the query method to return one result at most. If no result is found, "),a("code",[e._v("Mono.empty()")]),e._v(" is returned. More than one result triggers an "),a("code",[e._v("IncorrectResultSizeDataAccessException")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Maybe<T>")])]),e._v(" "),a("td",[e._v("A RxJava "),a("code",[e._v("Maybe")]),e._v(" emitting zero or one element using reactive repositories. Expects the query method to return one result at most. If no result is found, "),a("code",[e._v("Mono.empty()")]),e._v(" is returned. More than one result triggers an "),a("code",[e._v("IncorrectResultSizeDataAccessException")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("Flowable<T>")])]),e._v(" "),a("td",[e._v("A RxJava "),a("code",[e._v("Flowable")]),e._v(" emitting zero, one, or many elements using reactive repositories. Queries returning "),a("code",[e._v("Flowable")]),e._v(" can emit also an infinite number of elements.")])])])]),e._v(" "),a("hr"),e._v(" "),a("p",[a("a",{attrs:{href:"#_footnoteref_1"}},[e._v("1")]),e._v(". see "),a("a",{attrs:{href:"#repositories.create-instances.spring"}},[e._v("XML Configuration")])])])}),[],!1,null,null,null);t.default=r.exports}}]);