0.20.2 and above or optional dependency or not even that if you are using Embedded Node Client
</p></div></div><divclass="part"lang="en"><divclass="titlepage"><div><div><h1class="title"><aname="reference"></a>Part I. Reference Documentation</h1></div></div></div><divclass="chapter"lang="en"><divclass="titlepage"><div><div><h2class="title"><aname="repositories"></a>Chapter 1. Repositories</h2></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="repositories.introduction"></a>1.1. Introduction</h2></div></div></div><p>Implementing a data access layer of an application has been
cumbersome for quite a while. Too much boilerplate code had to be written.
Domain classes were anemic and not designed in a real object oriented or
domain driven manner.</p><p>Using both of these technologies makes developers life a lot easier
regarding rich domain model's persistence. Nevertheless the amount of
boilerplate code to implement repositories especially is still quite high.
So the goal of the repository abstraction of Spring Data is to reduce the
effort to implement data access layers for various persistence stores
significantly.</p><p>The following chapters will introduce the core concepts and
interfaces of Spring Data repositories in general for detailled
information on the specific features of a particular store consult the
later chapters of this document.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/admons/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>As this part of the documentation is pulled in from Spring Data
Commons we have to decide for a particular module to be used as example.
The configuration and code samples in this chapter are using the JPA
module. Make sure you adapt e.g. the XML namespace declaration, types to
be extended to the equivalents of the module you're actually
using.</p></td></tr></table></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="repositories.core-concepts"></a>1.2. Core concepts</h2></div></div></div><p>The central interface in Spring Data repository abstraction is
<codeclass="interfacename">Repository</code> (probably not that much of a
surprise). It is typeable to the domain class to manage as well as the id
type of the domain class. This interface mainly acts as marker interface
to capture the types to deal with and help us when discovering interfaces
that extend this one. Beyond that there's
<codeclass="interfacename">CrudRepository</code> which provides some
sophisticated functionality around CRUD for the entity being
managed.</p><divclass="example"><aname="repositories.repository"></a><pclass="title"><b>Example 1.1. <codeclass="interfacename">CrudRepository</code> interface</b></p><divclass="example-contents"><divclass="programlistingco"><preclass="programlisting"><spanclass="hl-keyword">public</span><spanclass="hl-keyword">interface</span> CrudRepository<T, ID <spanclass="hl-keyword">extends</span> Serializable>
<spanclass="hl-comment">// … more functionality omitted.</span>
}</pre><divclass="calloutlist"><tableborder="0"summary="Callout list"><tr><tdwidth="5%"valign="top"align="left"><imgsrc="images/callouts/1.png"alt="1"border="0"></td><tdvalign="top"align="left"><p>Saves the given entity.</p></td></tr><tr><tdwidth="5%"valign="top"align="left"><imgsrc="images/callouts/2.png"alt="2"border="0"></td><tdvalign="top"align="left"><p>Returns the entity identified by the given id.</p></td></tr><tr><tdwidth="5%"valign="top"align="left"><imgsrc="images/callouts/3.png"alt="3"border="0"></td><tdvalign="top"align="left"><p>Returns all entities.</p></td></tr><tr><tdwidth="5%"valign="top"align="left"><imgsrc="images/callouts/4.png"alt="4"border="0"></td><tdvalign="top"align="left"><p>Returns the number of entities.</p></td></tr><tr><tdwidth="5%"valign="top"align="left"><imgsrc="images/callouts/5.png"alt="5"border="0"></td><tdvalign="top"align="left"><p>Deletes the given entity.</p></td></tr><tr><tdwidth="5%"valign="top"align="left"><imgsrc="images/callouts/6.png"alt="6"border="0"></td><tdvalign="top"align="left"><p>Returns whether an entity with the given id exists.</p></td></tr></table></div></div></div></div><brclass="example-break"><p>Usually we will have persistence technology specific sub-interfaces
to include additional technology specific methods. We will now ship
implementations for a variety of Spring Data modules that implement this
interface.</p><p>On top of the <codeclass="interfacename">CrudRepository</code> there is
a <codeclass="interfacename">PagingAndSortingRepository</code> abstraction
that adds additional methods to ease paginated access to entities:</p><divclass="example"><aname="d0e116"></a><pclass="title"><b>Example 1.2. PagingAndSortingRepository</b></p><divclass="example-contents"><preclass="programlisting"><spanclass="hl-keyword">public</span><spanclass="hl-keyword">interface</span> PagingAndSortingRepository<T, ID <spanclass="hl-keyword">extends</span> Serializable><spanclass="hl-keyword">extends</span> CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}</pre></div></div><brclass="example-break"><p>Accessing the second page of <codeclass="classname">User</code> by a page
size of 20 you could simply do something like this:</p><preclass="programlisting">PagingAndSortingRepository<User, Long> repository = <spanclass="hl-comment">// … get access to a bean</span>
Page<User> users = repository.findAll(<spanclass="hl-keyword">new</span> PageRequest(1, 20));</pre></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="repositories.query-methods"></a>1.3. Query methods</h2></div></div></div><p>Next to standard CRUD functionality repositories are usually queries
on the underlying datastore. With Spring Data declaring those queries
becomes a four-step process:</p><divclass="orderedlist"><oltype="1"><li><p>Declare an interface extending
<codeclass="interfacename">Repository</code> or one of its sub-interfaces
and type it to the domain class it shall handle.</p><preclass="programlisting"><spanclass="hl-keyword">public</span><spanclass="hl-keyword">interface</span> PersonRepository <spanclass="hl-keyword">extends</span> Repository<User, Long> { … }</pre></li><li><p>Declare query methods on the interface.</p><preclass="programlisting">List<Person> findByLastname(String lastname);</pre></li><li><p>Setup Spring to create proxy instances for those
<<spanclass="hl-tag">/beans</span>></pre><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/admons/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>Note that we use the JPA namespace here just by example. If
you're using the repository abstraction for any other store you need
to change this to the appropriate namespace declaration of your
store module which should be exchanging <codeclass="code">jpa</code> in favor of
e.g. <codeclass="code">mongodb</code>.</p></td></tr></table></div></li><li><p>Get the repository instance injected and use it.</p><preclass="programlisting"><spanclass="hl-keyword">public</span><spanclass="hl-keyword">class</span> SomeClient {
}</pre></li></ol></div><p>At this stage we barely scratched the surface of what's possible
with the repositories but the general approach should be clear. Let's go
through each of these steps and figure out details and various options
that you have at each stage.</p><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="repositories.definition"></a>1.3.1. Defining repository interfaces</h3></div></div></div><p>As a very first step you define a domain class specific repository
interface. It's got to extend <codeclass="interfacename">Repository</code>
and be typed to the domain class and an ID type. If you want to expose
CRUD methods for that domain type, extend
<codeclass="interfacename">CrudRepository</code> instead of
<codeclass="interfacename">Repository</code>.</p><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.definition-tuning"></a>1.3.1.1. Fine tuning repository definition</h4></div></div></div><p>Usually you will have your repository interface extend
<codeclass="interfacename">Repository</code>,
<codeclass="interfacename">CrudRepository</code> or
<codeclass="interfacename">PagingAndSortingRepository</code>. If you
don't like extending Spring Data interfaces at all you can also
User findByEmailAddress(EmailAddress emailAddress);
}</pre></div></div><brclass="example-break"><p>In the first step we define a common base interface for all our
domain repositories and expose <codeclass="methodname">findOne(…)</code> as
well as <codeclass="methodname">save(…)</code>.These methods will be routed
into the base repository implementation of the store of your choice
because they are matching the method signatures in
<codeclass="interfacename">CrudRepository</code>. So our
<codeclass="interfacename">UserRepository</code> will now be able to save
users, find single ones by id as well as triggering a query to find
<codeclass="interfacename">User</code>s by their email address.</p></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="repositories.query-methods.details"></a>1.3.2. Defining query methods</h3></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.query-methods.query-lookup-strategies"></a>1.3.2.1. Query lookup strategies</h4></div></div></div><p>The next thing we have to discuss is the definition of query
methods. There are two main ways that the repository proxy is able to
come up with the store specific query from the method name. The first
option is to derive the query from the method name directly, the
second is using some kind of additionally created query. What detailed
options are available pretty much depends on the actual store,
however, there's got to be some algorithm that decides what actual
query is created.</p><p>There are three strategies available for the repository
infrastructure to resolve the query. The strategy to be used can be
configured at the namespace through the
<codeclass="code">query-lookup-strategy</code> attribute. However, It might be the
case that some of the strategies are not supported for specific
datastores. Here are your options:</p><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h5class="title"><aname="d0e240"></a>CREATE</h5></div></div></div><p>This strategy will try to construct a store specific query
from the query method's name. The general approach is to remove a
given set of well-known prefixes from the method name and parse the
rest of the method. Read more about query construction in <ahref="#repositories.query-methods.query-creation"title="1.3.2.2. Query creation">Section 1.3.2.2, “Query creation”</a>.</p></div><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h5class="title"><aname="d0e247"></a>USE_DECLARED_QUERY</h5></div></div></div><p>This strategy tries to find a declared query which will be
used for execution first. The query could be defined by an
annotation somewhere or declared by other means. Please consult the
documentation of the specific store to find out what options are
available for that store. If the repository infrastructure does not
find a declared query for the method at bootstrap time it will
fail.</p></div><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h5class="title"><aname="d0e252"></a>CREATE_IF_NOT_FOUND (default)</h5></div></div></div><p>This strategy is actually a combination of <codeclass="code">CREATE</code>
and <codeclass="code">USE_DECLARED_QUERY</code>. It will try to lookup a
declared query first but create a custom method name based query if
no declared query was found. This is the default lookup strategy and
thus will be used if you don't configure anything explicitly. It
allows quick query definition by method names but also custom tuning
of these queries by introducing declared queries as needed.</p></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.query-methods.query-creation"></a>1.3.2.2. Query creation</h4></div></div></div><p>The query builder mechanism built into Spring Data repository
infrastructure is useful to build constraining queries over entities
of the repository. We will strip the prefixes <codeclass="code">findBy</code>,
<codeclass="literal">GreaterThan</code>, <codeclass="literal">Like</code> for the
property expressions. As the operators supported can vary from
datastore to datastore please consult the according part of the
reference documentation.</p><divclass="section"lang="en"><divclass="titlepage"><div><div><h5class="title"><aname="repositories.query-methods.property-expressions"></a>1.3.2.2.1. Property expressions</h5></div></div></div><p>Property expressions can just refer to a direct property of
the managed entity (as you just saw in the example above). On query
creation time we already make sure that the parsed property is at a
property of the managed domain class. However, you can also define
constraints by traversing nested properties. Assume
<codeclass="classname">Person</code>s have <codeclass="classname">Address</code>es
with <codeclass="classname">ZipCode</code>s. In that case a method name
of</p><preclass="programlisting">List<Person> findByAddressZipCode(ZipCode zipCode);</pre><p>will create the property traversal
<codeclass="code">x.address.zipCode</code>. The resolution algorithm starts with
interpreting the entire part (<codeclass="literal">AddressZipCode</code>) as
property and checks the domain class for a property with that name
(uncapitalized). If it succeeds it just uses that. If not it starts
splitting up the source at the camel case parts from the right side
into a head and a tail and tries to find the according property,
e.g. <codeclass="literal">AddressZip</code> and <codeclass="literal">Code</code>. If
we find a property with that head we take the tail and continue
building the tree down from there. As in our case the first split
does not match we move the split point to the left
(<codeclass="literal">Address</code>, <codeclass="literal">ZipCode</code>).</p><p>Although this should work for most cases, there might be cases
where the algorithm could select the wrong property. Suppose our
<codeclass="classname">Person</code> class has an <codeclass="code">addressZip</code>
property as well. Then our algorithm would match in the first split
round already and essentially choose the wrong property and finally
fail (as the type of <codeclass="classname">addressZip</code> probably has
no code property). To resolve this ambiguity you can use
<codeclass="literal">_</code> inside your method name to manually define
traversal points. So our method name would end up like so:</p><preclass="programlisting">List<Person> findByAddress_ZipCode(ZipCode zipCode);
</pre></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.special-parameters"></a>1.3.2.3. Special parameter handling</h4></div></div></div><p>To hand parameters to your query you simply define method
parameters as already seen in the examples above. Besides that we will
recognizes certain specific types to apply pagination and sorting to
your queries dynamically.</p><divclass="example"><aname="d0e369"></a><pclass="title"><b>Example 1.5. Using Pageable and Sort in query methods</b></p><divclass="example-contents"><preclass="programlisting">Page<User> findByLastname(String lastname, Pageable pageable);
List<User> findByLastname(String lastname, Pageable pageable);</pre></div></div><brclass="example-break"><p>The first method allows you to pass a <codeclass="code">Pageable</code>
instance to the query method to dynamically add paging to your
statically defined query. <codeclass="code">Sorting</code> options are handed via
the <codeclass="interfacename">Pageable</code> instance too. If you only
need sorting, simply add a <codeclass="code">Sort</code> parameter to your method.
As you also can see, simply returning a
<codeclass="interfacename">List</code> is possible as well. We will then
not retrieve the additional metadata required to build the actual
<codeclass="interfacename">Page</code> instance but rather simply
restrict the query to lookup only the given range of entities.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/admons/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>To find out how many pages you get for a query entirely we
have to trigger an additional count query. This will be derived from
the query you actually trigger by default.</p></td></tr></table></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="repositories.create-instances"></a>1.3.3. Creating repository instances</h3></div></div></div><p>So now the question is how to create instances and bean
definitions for the repository interfaces defined.</p><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.create-instances.spring"></a>1.3.3.1. XML Configuration</h4></div></div></div><p>The easiest way to do so is by using the Spring namespace that
is shipped with each Spring Data module that supports the repository
mechanism. Each of those includes a repositories element that allows
you to simply define a base package that Spring will scan for
<<spanclass="hl-tag">/beans:beans</span>></pre><p>In this case we instruct Spring to scan
<spanclass="package">com.acme.repositories</span> and all its sub packages for
interfaces extending <codeclass="interfacename">Repository</code> or one
of its sub-interfaces. For each interface found it will register the
persistence technology specific
<codeclass="interfacename">FactoryBean</code> to create the according
proxies that handle invocations of the query methods. Each of these
beans will be registered under a bean name that is derived from the
interface name, so an interface of
<codeclass="interfacename">UserRepository</code> would be registered
under <codeclass="code">userRepository</code>. The <codeclass="code">base-package</code>
attribute allows the use of wildcards, so that you can have a pattern
of scanned packages.</p><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h5class="title"><aname="d0e429"></a>Using filters</h5></div></div></div><p>By default we will pick up every interface extending the
persistence technology specific
<codeclass="interfacename">Repository</code> sub-interface located
underneath the configured base package and create a bean instance
for it. However, you might want finer grained control over which
interfaces bean instances get created for. To do this we support the
use of <codeclass="code"><include-filter /></code> and
<codeclass="code"><exclude-filter /></code> elements inside
<codeclass="code"><repositories /></code>. The semantics are exactly
equivalent to the elements in Spring's context namespace. For
details see <axmlns:xlink="http://www.w3.org/1999/xlink"href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-scanning-filters"target="_top">Spring reference documentation</a> on these
elements.</p><p>E.g. to exclude certain interfaces from instantiation as
repository, you could use the following configuration:</p><divclass="example"><aname="d0e451"></a><pclass="title"><b>Example 1.6. Using exclude-filter element</b></p><divclass="example-contents"><preclass="programlisting"><<spanclass="hl-tag">repositories</span><spanclass="hl-attribute">base-package</span>=<spanclass="hl-value">"com.acme.repositories"</span>>
<<spanclass="hl-tag">/repositories</span>></pre><p>This would exclude all interfaces ending in
<codeclass="interfacename">SomeRepository</code> from being
instantiated.</p></div></div><brclass="example-break"></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.create-instances.java-config"></a>1.3.3.2. JavaConfig</h4></div></div></div><p>The repository infrastructure can also be triggered using a
on a JavaConfig class. For an introduction into Java based
configuration of the Spring container please have a look at the
reference documentation.<sup>[<aname="d0e469"href="#ftn.d0e469">1</a>]</sup></p><p>A sample configuration to enable Spring Data repositories would
look something like this.</p><divclass="example"><aname="d0e475"></a><pclass="title"><b>Example 1.7. Sample annotation based repository configuration</b></p><divclass="example-contents"><preclass="programlisting">@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {
@Bean
public EntityManagerFactory entityManagerFactory() {
// …
}
}</pre></div></div><brclass="example-break"><p>Note that the sample uses the JPA specific annotation which
would have to be exchanged dependingon which store module you actually
consult the sections covering the store-specific configuration.</p></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="repositories.create-instances.standalone"></a>1.3.3.3. Standalone usage</h4></div></div></div><p>You can also use the repository infrastructure outside of a
Spring container usage. You will still need to have some of the Spring
libraries on your classpath but you can generally setup repositories
programmatically as well. The Spring Data modules providing repository
support ship a persistence technology specific
<codeclass="classname">RepositoryFactory</code> that can be used as
UserRepository repository = factory.getRepository(UserRepository.<spanclass="hl-keyword">class</span>);</pre></div></div><brclass="example-break"></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="repositories.custom-implementations"></a>1.4. Custom implementations</h2></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="repositories.single-repository-behaviour"></a>1.4.1. Adding behaviour to single repositories</h3></div></div></div><p>Often it is necessary to provide a custom implementation for a few
repository methods. Spring Data repositories easily allow you to provide
custom repository code and integrate it with generic CRUD abstraction
and query method functionality. To enrich a repository with custom
functionality you have to define an interface and an implementation for
that functionality first and let the repository interface you provided
so far extend that custom interface.</p><divclass="example"><aname="d0e506"></a><pclass="title"><b>Example 1.9. Interface for custom repository functionality</b></p><divclass="example-contents"><preclass="programlisting"><spanclass="hl-keyword">interface</span> UserRepositoryCustom {
<spanclass="hl-comment">// Your custom implementation</span>
}
}</pre><p>Note that the implementation itself does not depend on
Spring Data and can be a regular Spring bean. So you can use standard
dependency injection behaviour to inject references to other beans,
take part in aspects and so on.</p></div></div><brclass="example-break"><divclass="example"><aname="d0e518"></a><pclass="title"><b>Example 1.11. Changes to the your basic repository interface</b></p><divclass="example-contents"><preclass="programlisting"><spanclass="hl-keyword">public</span><spanclass="hl-keyword">interface</span> UserRepository <spanclass="hl-keyword">extends</span> CrudRepository<User, Long>, UserRepositoryCustom {
}</pre><p>Let your standard repository interface extend the custom
one. This makes CRUD and custom functionality available to
clients.</p></div></div><brclass="example-break"><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="d0e525"></a>Configuration</h4></div></div></div><p>If you use namespace configuration the repository infrastructure
tries to autodetect custom implementations by looking up classes in
the package we found a repository using the naming conventions
appending the namespace element's attribute
<codeclass="code">repository-impl-postfix</code> to the classname. This suffix
defaults to <codeclass="code">Impl</code>.</p><divclass="example"><aname="d0e536"></a><pclass="title"><b>Example 1.12. Configuration example</b></p><divclass="example-contents"><preclass="programlisting"><<spanclass="hl-tag">repositories</span><spanclass="hl-attribute">base-package</span>=<spanclass="hl-value">"com.acme.repository"</span> />
<<spanclass="hl-tag">repositories</span><spanclass="hl-attribute">base-package</span>=<spanclass="hl-value">"com.acme.repository"</span><spanclass="hl-attribute">repository-impl-postfix</span>=<spanclass="hl-value">"FooBar"</span> /></pre></div></div><brclass="example-break"><p>The first configuration example will try to lookup a class
<codeclass="classname">com.acme.repository.UserRepositoryImpl</code> to act
as custom repository implementation, where the second example will try
to lookup
<codeclass="classname">com.acme.repository.UserRepositoryFooBar</code>.</p></div><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="d0e550"></a>Manual wiring</h4></div></div></div><p>The approach above works perfectly well if your custom
implementation uses annotation based configuration and autowiring
entirely as it will be treated as any other Spring bean. If your
custom implementation bean needs some special wiring you simply
declare the bean and name it after the conventions just described. We
will then pick up the custom bean by name rather than creating an
instance.</p><divclass="example"><aname="d0e555"></a><pclass="title"><b>Example 1.13. Manual wiring of custom implementations (I)</b></p><divclass="example-contents"><preclass="programlisting"><<spanclass="hl-tag">repositories</span><spanclass="hl-attribute">base-package</span>=<spanclass="hl-value">"com.acme.repository"</span> />
<<spanclass="hl-comment">!-- further configuration --</span>>
<<spanclass="hl-tag">/beans:bean</span>></pre></div></div><brclass="example-break"></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="repositories.custom-behaviour-for-all-repositories"></a>1.4.2. Adding custom behaviour to all repositories</h3></div></div></div><p>In other cases you might want to add a single method to all of
your repository interfaces. So the approach just shown is not feasible.
The first step to achieve this is adding and intermediate interface to
declare the shared behaviour</p><divclass="example"><aname="d0e565"></a><pclass="title"><b>Example 1.14. An interface declaring custom shared behaviour</b></p><divclass="example-contents"><preclass="programlisting">
<spanclass="hl-keyword">public</span><spanclass="hl-keyword">interface</span> MyRepository<T, ID <spanclass="hl-keyword">extends</span> Serializable>
}</pre></div></div><brclass="example-break"><p>Now your individual repository interfaces will extend this
intermediate interface instead of the
<codeclass="interfacename">Repository</code> interface to include the
functionality declared. The second step is to create an implementation
of this interface that extends the persistence technology specific
repository base class which will then act as a custom base class for the
repository proxies.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/admons/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>The default behaviour of the Spring <codeclass="code"><repositories
/></code> namespace is to provide an implementation for all
interfaces that fall under the <codeclass="code">base-package</code>. This means
that if left in it's current state, an implementation instance of
<codeclass="interfacename">MyRepository</code> will be created by Spring.
This is of course not desired as it is just supposed to act as an
intermediary between <codeclass="interfacename">Repository</code> and the
actual repository interfaces you want to define for each entity. To
exclude an interface extending
<codeclass="interfacename">Repository</code> from being instantiated as a
repository instance it can either be annotate it with
<codeclass="interfacename">@NoRepositoryBean</code> or moved out side of
the configured <codeclass="code">base-package</code>.</p></td></tr></table></div><divclass="example"><aname="d0e600"></a><pclass="title"><b>Example 1.15. Custom repository base class</b></p><divclass="example-contents"><preclass="programlisting">
<spanclass="hl-keyword">public</span><spanclass="hl-keyword">class</span> MyRepositoryImpl<T, ID <spanclass="hl-keyword">extends</span> Serializable>
}</pre></div></div><brclass="example-break"><p>The last step is to create a custom repository factory to replace
the default <codeclass="classname">RepositoryFactoryBean</code> that will in
turn produce a custom <codeclass="classname">RepositoryFactory</code>. The new
repository factory will then provide your
<codeclass="classname">MyRepositoryImpl</code> as the implementation of any
interfaces that extend the <codeclass="interfacename">Repository</code>
interface, replacing the <codeclass="classname">SimpleJpaRepository</code>
implementation you just extended.</p><divclass="example"><aname="d0e622"></a><pclass="title"><b>Example 1.16. Custom repository factory bean</b></p><divclass="example-contents"><preclass="programlisting">
<spanclass="hl-keyword">public</span><spanclass="hl-keyword">class</span> MyRepositoryFactoryBean<R <spanclass="hl-keyword">extends</span> JpaRepository<T, I>, T, I <spanclass="hl-keyword">extends</span> Serializable>
}</pre></div></div><brclass="example-break"><p>Finally you can either declare beans of the custom factory
directly or use the <codeclass="code">factory-class</code> attribute of the Spring
namespace to tell the repository infrastructure to use your custom
factory implementation.</p><divclass="example"><aname="d0e632"></a><pclass="title"><b>Example 1.17. Using the custom factory with the namespace</b></p><divclass="example-contents"><preclass="programlisting"><<spanclass="hl-tag">repositories</span><spanclass="hl-attribute">base-package</span>=<spanclass="hl-value">"com.acme.repository"</span>
<spanclass="hl-attribute">factory-class</span>=<spanclass="hl-value">"com.acme.MyRepositoryFactoryBean"</span> /></pre></div></div><brclass="example-break"></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="d0e637"></a>1.5. Extensions</h2></div></div></div><p>This chapter documents a set of Spring Data extensions that enable
Spring Data usage in a variety of contexts. Currently most of the
integration is targeted towards Spring MVC.</p><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="web-domain-class-binding"></a>1.5.1. Domain class web binding for Spring MVC</h3></div></div></div><p>Given you are developing a Spring MVC web applications you
typically have to resolve domain class ids from URLs. By default it's
your task to transform that request parameter or URL part into the
domain class to hand it layers below then or execute business logic on
the entities directly. This should look something like this:</p><preclass="programlisting">@Controller
}</pre><p>First you pretty much have to declare a repository dependency for
each controller to lookup the entity managed by the controller or
repository respectively. Beyond that looking up the entity is
boilerplate as well as it's always a <codeclass="methodname">findOne(…)</code>
call. Fortunately Spring provides means to register custom converting
components that allow conversion between a <codeclass="classname">String</code>
value to an arbitrary type.</p><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="d0e657"></a>PropertyEditors</h4></div></div></div><p>For versions up to Spring 3.0 simple Java
<codeclass="interfacename">PropertyEditor</code>s had to be used. Thus,
we offer a <codeclass="classname">DomainClassPropertyEditorRegistrar</code>,
that will look up all Spring Data repositories registered in the
<codeclass="interfacename">ApplicationContext</code> and register a
custom <codeclass="interfacename">PropertyEditor</code> for the managed
}</pre></div><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="d0e680"></a>ConversionService</h4></div></div></div><p>As of Spring 3.0 the
<codeclass="interfacename">PropertyEditor</code> support is superseeded
by a new conversion infrstructure that leaves all the drawbacks of
<codeclass="interfacename">PropertyEditor</code>s behind and uses a
stateless X to Y conversion approach. We now ship with a
<codeclass="classname">DomainClassConverter</code> that pretty much mimics
the behaviour of
<codeclass="classname">DomainClassPropertyEditorRegistrar</code>. To register
the converter you have to declare
<codeclass="classname">ConversionServiceFactoryBean</code>, register the
converter and tell the Spring MVC namespace to use the configured
}</pre><p>As you can see the naive approach requires the method to contain
an <codeclass="interfacename">HttpServletRequest</code> parameter that has
to be parsed manually. We even omitted an appropriate failure handling
which would make the code even more verbose. The bottom line is that the
controller actually shouldn't have to handle the functionality of
extracting pagination information from the request. So we include a
<codeclass="classname">PageableArgumentResolver</code> that will do the work
for you.</p><preclass="programlisting"><<spanclass="hl-tag">bean</span><spanclass="hl-attribute">class</span>=<spanclass="hl-value">"….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"</span>>
}</pre><p>The <codeclass="classname">PageableArgumentResolver</code> will
automatically resolve request parameters to build a
<codeclass="classname">PageRequest</code> instance. By default it will expect
the following structure for the request parameters:</p><divclass="table"><aname="d0e729"></a><pclass="title"><b>Table 1.1. Request parameters evaluated by
<codeclass="classname">PageableArgumentResolver</code></b></p><divclass="table-contents"><tablesummary="Request parameters evaluated by
 PageableArgumentResolver"border="1"><colgroup><col><col></colgroup><tbody><tr><td><codeclass="code">page</code></td><td>The page you want to retrieve</td></tr><tr><td><codeclass="code">page.size</code></td><td>The size of the page you want to retrieve</td></tr><tr><td><codeclass="code">page.sort</code></td><td>The property that should be sorted by</td></tr><tr><td><codeclass="code">page.sort.dir</code></td><td>The direction that should be used for sorting</td></tr></tbody></table></div></div><brclass="table-break"><p>In case you need multiple <codeclass="interfacename">Pageable</code>s
to be resolved from the request (for multiple tables e.g.) you can use
Spring's <codeclass="interfacename">@Qualifier</code> annotation to
distinguish one from another. The request parameters then have to be
prefixed with <codeclass="code">${qualifier}_</code>. So a method signature like
</pre><p>you'd have to populate <codeclass="code">foo_page</code> and
<codeclass="code">bar_page</code> and the according subproperties.</p><divclass="simplesect"lang="en"><divclass="titlepage"><div><div><h4class="title"><aname="d0e783"></a>Defaulting</h4></div></div></div><p>The <codeclass="classname">PageableArgumentResolver</code> will use a
<codeclass="classname">PageRequest</code> with the first page and a page size
of 10 by default and will use that in case it can't resolve a
<codeclass="classname">PageRequest</code> from the request (because of
missing parameters e.g.). You can configure a global default on the
bean declaration directly. In case you might need controller method
specific defaults for the <codeclass="interfacename">Pageable</code>
simply annotate the method parameter with
<codeclass="interfacename">@PageableDefaults</code> and specify page and
page size as annotation attributes:</p><preclass="programlisting"><spanclass="hl-keyword">public</span> String showUsers(Model model,
</pre></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="d0e805"></a>1.5.3. Repository populators</h3></div></div></div><p>If you have been working with the JDBC module of Spring you're
probably familiar with the support to populate a DataSource using SQL
scripts. A similar abstraction is available on the repositories level
although we don't use SQL as data definition language as we need to be
store independent of course. Thus the populators support XML (through
Spring's OXM abstraction) and JSON (through Jackson) to define data for
the repositories to be populated with.</p><p>Assume you have a file <codeclass="filename">data.json</code> with the
following content:</p><divclass="example"><aname="d0e815"></a><pclass="title"><b>Example 1.18. Data defined in JSON</b></p><divclass="example-contents"><preclass="programlisting">[ { "_class" : "com.acme.Person",
"firstname" : "Dave",
"lastname" : "Matthews" },
{ "_class" : "com.acme.Person",
"firstname" : "Carter",
"lastname" : "Beauford" } ]</pre></div></div><brclass="example-break"><p>You can easily populate you repositories by using the populator
elements of the repository namespace provided in Spring Data Commons. To
get the just shown data be populated to your
<codeclass="interfacename">PersonRepository</code> all you need to do is
the following:</p><divclass="example"><aname="d0e825"></a><pclass="title"><b>Example 1.19. Declaring a Jackson repository populator</b></p><divclass="example-contents"><preclass="programlisting"><<spanclass="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>>
<<spanclass="hl-tag">/beans</span>></pre></div></div><brclass="example-break"><p>This declaration causes the data.json file being read,
deserialized by a Jackson <codeclass="classname">ObjectMapper</code>. The type
the JSON object will be unmarshalled to will be determined by inspecting
the <codeclass="code">_class</code> attribute of the JSON document. We will
eventually select the appropriate repository being able to handle the
object just deserialized.</p><p>To rather use XML to define the repositories shall be populated
with you can use the unmarshaller-populator you hand one of the
marshaller options Spring OXM provides you with.</p><divclass="example"><aname="d0e840"></a><pclass="title"><b>Example 1.20. Declaring an unmarshalling repository populator (using
<<spanclass="hl-tag">/beans</span>></pre></div></div><brclass="example-break"></div></div><divclass="footnotes"><br><hrwidth="100"align="left"><divclass="footnote"><p><sup>[<aname="ftn.d0e469"href="#d0e469">1</a>] </sup>JavaConfig in the Spring reference documentation - <axmlns:xlink="http://www.w3.org/1999/xlink"href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java"target="_top">http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java</a></p></div></div></div><divclass="chapter"lang="en"><divclass="titlepage"><div><div><h2class="title"><aname="elasticsearch.repositories"></a>Chapter 2. Elasticsearch Repositories</h2></div></div></div><divclass="abstract"><pclass="title"><b>Abstract</b></p><p>This chapter includes details of the Elasticsearch repository
</p><divclass="example"><aname="d0e869"></a><pclass="title"><b>Example 2.1. Setting up Elasticsearch repositories using Namespace</b></p><divclass="example-contents"><preclass="programlisting"><<spanclass="hl-tag">?xml version="1.0" encoding="UTF-8"?</span>>
</p></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="elasticsearch.annotation"></a>2.1.2. Annotation based configuration</h3></div></div></div><p>The Spring Data Elasticsearch repositories support cannot only be
activated through an XML namespace but also using an annotation
through JavaConfig.
</p><divclass="example"><aname="d0e902"></a><pclass="title"><b>Example 2.4. Spring Data Elasticsearch repositories using JavaConfig</b></p><divclass="example-contents"><preclass="programlisting">
essentially carries the same attributes as the XML
namespace does. If no
base package is configured, it will use the
one
the configuration class
resides in.
</p></div></div><brclass="example-break"></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h3class="title"><aname="elasticsearch.cdi"></a>2.1.3. Elasticsearch Repositores using CDI</h3></div></div></div><p>The Spring Data Elasticsearch repositories can also be set up using CDI
functionality.
</p><divclass="example"><aname="d0e923"></a><pclass="title"><b>Example 2.5. Spring Data Elasticsearch repositories using JavaConfig</b></p><divclass="example-contents"><preclass="programlisting"><spanclass="hl-keyword">class</span> ElasticsearchTemplateProducer {
</pre></div></div><brclass="example-break"></div></div></div><divclass="part"lang="en"><divclass="titlepage"><div><div><h1class="title"><aname="appendix"></a>Part II. Appendix</h1></div></div></div><divclass="appendix"lang="en"><divclass="titlepage"><div><div><h2class="title"><aname="namespace-reference"></a>Appendix A. Namespace reference</h2></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="namespace-dao-config"></a>A.1. The <codeclass="code"><repositories /></code> element</h2></div></div></div><p>The <codeclass="code"><repositories /></code> triggers the setup of the
Spring Data repository infrastructure. The most important attribute is
<codeclass="code">base-package</code> which defines the package to scan for Spring
Data repository interfaces.<sup>[<aname="d0e1352"href="#ftn.d0e1352">2</a>]</sup></p><divclass="table"><aname="d0e1356"></a><pclass="title"><b>Table A.1. Attributes</b></p><divclass="table-contents"><tablesummary="Attributes"border="1"><colgroup><col><col></colgroup><thead><tr><th>Name</th><th>Description</th></tr></thead><tbody><tr><td><codeclass="code">base-package</code></td><td>Defines the package to be used to be scanned for repository
(actual interface is determined by specific Spring Data module) in
auto detection mode. All packages below the configured package
will be scanned, too. Wildcards are also allowed.</td></tr><tr><td><codeclass="code">repository-impl-postfix</code></td><td>Defines the postfix to autodetect custom repository
implementations. Classes whose names end with the configured
postfix will be considered as candidates. Defaults to
<codeclass="code">Impl</code>.</td></tr><tr><td><codeclass="code">query-lookup-strategy</code></td><td>Determines the strategy to be used to create finder
queries. See <ahref="#repositories.query-methods.query-lookup-strategies"title="1.3.2.1. Query lookup strategies">Section 1.3.2.1, “Query lookup strategies”</a> for
details. Defaults to <codeclass="code">create-if-not-found</code>.</td></tr></tbody></table></div></div><brclass="table-break"></div><divclass="footnotes"><br><hrwidth="100"align="left"><divclass="footnote"><p><sup>[<aname="ftn.d0e1352"href="#d0e1352">2</a>] </sup>see <ahref="#repositories.create-instances.spring"title="1.3.3.1. XML Configuration">Section 1.3.3.1, “XML Configuration”</a></p></div></div></div><divclass="appendix"lang="en"><divclass="titlepage"><div><div><h2class="title"><aname="repository-query-keywords"></a>Appendix B. Repository query keywords</h2></div></div></div><divclass="section"lang="en"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="d0e1401"></a>B.1. Supported query keywords</h2></div></div></div><p>The following table lists the keywords generally supported by the
Spring data repository query derivation mechanism. However consult the
store specific documentation for the exact list of supported keywords as
some of the ones listed here might not be supported in a particular
<codeclass="literal">IsGreaterThanEqual</code></td></tr><tr><td><codeclass="code">IN</code></td><td><codeclass="literal">In</code>, <codeclass="literal">IsIn</code></td></tr><tr><td><codeclass="code">IS</code></td><td><codeclass="literal">Is</code>, <codeclass="literal">Equals</code>, (or no