Spring Data Reference

Core Spring Data Cheat Sheet

Converted from the supplied seven-page DZone Core Spring Data refcard into the same navigable HTML reference style used for the earlier cheat sheets. The source covers configuration, object mapping, templates, repositories, query derivation, pagination, Querydsl, CDI, Spring MVC integration and Spring Data REST. fileciteturn4file0L28-L38

Source scope: The supplied document is a DZone “Core Spring Data” refcard by Oliver Gierke. Its contents include About the Spring Data Project, Configuration Support, Object Mapping, Template APIs, Repositories and Advanced Features. fileciteturn4file0L122-L129

About the Spring Data Project

The Spring Data project is part of the ecosystem surrounding the Spring Framework and constitutes an umbrella project for advanced data access related topics. It contains modules to support traditional relational data stores (based on plain JDBC or JPA), NoSQL stores such as MongoDB, Neo4j or Redis, and big data technologies like Apache Hadoop.

General Themes

The core mission is to provide a familiar and consistent Spring-based programming model for various data access technologies while retaining store-specific features and capabilities.

Infrastructure Configuration Support

Spring Data supports configuring resources to access the underlying technology. The support is implemented using XML namespaces and Spring JavaConfig, with integration with core Spring functionality such as JMX.

Object Mapping Framework

Spring Data provides a mapping and conversion API that allows obtaining metadata about domain classes to be persisted and converting arbitrary domain objects into store-specific data types.

Template APIs

Spring Data provides template-pattern APIs such as RedisTemplate and MongoTemplate. Templates provide helper methods, resource management, exception translation, and callback APIs for access to store-native APIs.

Repository Abstraction

Spring Data provides a repository abstraction on top of template implementations. It reduces the effort needed to implement data access objects to plain interface definitions for common scenarios such as standard CRUD operations while retaining access to store-specific features.

Configuration Support

At the lowest level, Spring Data provides support to configure infrastructure components and enable features such as repository support. Individual modules provide Spring XML namespaces and, where reasonable, JavaConfig equivalents implemented as @Enable... annotations.

Object Mapping

Spring Data provides annotation-based mapping support for different persistence technologies. The supplied refcard shows JPA, MongoDB and Neo4j examples.

Template APIs

Spring Data template implementations have three major responsibilities: transparent integration of object-to-store mapping, resource management, and exception translation into Spring's DataAccessException hierarchy.

Three responsibilities

1. Transparent integration of object-to-store mapping. 2. Resource management, including reliably acquiring and releasing connections. 3. Exception translation from persistence-specific exceptions into Spring's DataAccessException hierarchy.

Three groups of methods

1. Standard use-case methods such as findOne(...) and findAll(...). 2. Store-specific functionality such as createCollection(...) / geoNear(...) for MongoDB or createNode(...) / traverse(...) for Neo4j. 3. Low-level execute(...) methods accepting callback interfaces for access to the native API.

Repositories

Spring Data uses an interface-based programming model to reduce repetitive repository boilerplate. The general quickstart is to create a repository interface, add query methods, and optionally add custom implementation where necessary.

Quickstart

1. Create an interface annotated with @RepositoryDefinition or extend one of Spring Data's base repository interfaces. 2. Add query methods and customize as needed. 3. Potentially add a custom implementation if necessary.

CustomerRepository example

interface CustomerRepository extends Repository<Customer, Long> { Customer findByEmailAddress(EmailAddress email); List<Customer> findByAddressCity(String city); Page<Customer> findByLastnameLike(String lastname, Pageable pageable); }

Query Derivation Mechanism

A query method declaration causes the Spring Data repository infrastructure to parse the method name into a store-specific query. The method name consists of a prefix, a property reference (and potentially nested properties), and optional keywords defining how parameters are bound.

Customizing Query Execution

When query derivation is insufficient, the modules provide @Query to customize the query to execute.

Custom query example

interface CustomerRepository extends Repository<Customer, Long> { @Query("select c from Customer c where c.emailAddress = ?1") Customer findByEmailAddress(EmailAddress email); }

Pagination and Sorting

PagingAndSortingRepository provides an API for sorting and page-by-page access. The core abstractions are Sort and Pageable, while Page captures result metadata such as total pages and whether the current page is first or last.

Example

// Create request for the 2nd page by a page size of 10 Sort sort = new Sort(Direction.ASC, "lastname", "firstname"); Pageable pageable = new PageRequest(1, 10, sort); Page<Customer> customers = repository.findAll(pageable); assertThat(customers.isFirstPage(), is(false)); assertThat(customers.hasNextPage(), is(true)); for (Customer customer : customers) { // ... do something with the Customer }

Request parameters

page — page number, 0-indexed, defaults to 0 size — page size, defaults to 20 sort — comma-separated field references followed by asc or desc, e.g. /?sort=firstname,asc&lastname=desc

Customization annotations

@Qualifier — supports multiple pages or sorts by prefixing parameters. @PageableDefault — customizes Pageable defaults. @SortDefault — customizes Sort defaults.

Advanced Features

Spring Data also provides integration with third-party projects and technologies. The supplied refcard highlights Querydsl, CDI integration, Spring/SpringMVC integration, and Spring Data REST.

Querydsl

Querydsl brings LINQ-style, language-integrated query capabilities to Java. It is centered around a meta-model generated from domain classes, which can be used to define predicates and execute them through a Spring Data repository.

Predicate execution

A repository can extend QueryDslPredicateExecutor to expose the predicate execution API.

CDI Integration

The Spring Data modules ship with a CDI extension for using repository abstraction in a JavaEE environment with CDI dependency injection. The refcard outlines four steps: include the necessary Spring Data JARs, declare infrastructure components as CDI beans, declare repository interfaces, and inject repositories using @Inject.

Spring and SpringMVC Integration

Spring Data Commons provides support classes including DomainClassConverter, DomainClassPropertyEditor, SortHandlerMethodArgumentResolver and PageableHandlerMethodArgumentResolver.

Spring Data REST

Spring Data REST automatically exports repository-managed entities in a hypermedia-driven way. The refcard describes customizable JSON representations and extension/customization hooks for validation, security and integration.

Configuration Support

The refcard lists XML namespace elements and JavaConfig support for JPA, MongoDB and Neo4j. fileciteturn4file0L81-L103

StoreXML element / featureDescription
JPA<jpa:repositories />Enables Spring Data repositories support. JavaConfig equivalent: @EnableJpaRepositories.
JPA<jpa:auditing />Enables transparent auditing of JPA managed entities; requires the appropriate auditing entity listener.
MongoDB<mongo:repositories />Enables MongoDB repository support. JavaConfig equivalent: @EnableMongoRepositories.
MongoDB<mongo:auditing />Enables transparent auditing of MongoDB persisted domain objects.
MongoDB<mongo:jmx />Enables exposing MongoDB statistics and configuration as JMX MBeans.
Neo4j<neo4j:config />Configures the Neo4j data store connection and entity types to scan.
Neo4j<neo4j:repositories />Enables Neo4j repository support. JavaConfig equivalent: @EnableNeo4jRepositories.
Neo4j<neo4j:auditing />Enables transparent auditing of Neo4j mapped entities.

Object Mapping Examples

JPA Customer

@Entity
public class Customer {
    @Id @GeneratedValue
    private Long id;
    private String firstname, lastname;
    @Column(unique = true)
    private EmailAddress emailAddress;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "customer_id")
    private Set<Address> addresses = new HashSet<Address>();
    ...
}

Spring Data JPA supports JPA mapping annotations and essentially does not deal with the mapping itself. fileciteturn4file0L167-L182

MongoDB Customer

@Document
public class Customer {
    @Id
    private BigInteger id;
    private String firstname, lastname;
    @Field("email")
    @Indexed(unique = true)
    private EmailAddress emailAddress;
    private Set<Address> addresses = new HashSet<Address>();
    ...
}

Neo4j Customer

@NodeEntity
public class Customer {
    @GraphId
    private Long id;
    private String firstName, lastName;
    @Indexed(unique = true)
    private String emailAddress;
    @RelatedTo(type = "ADDRESS")
    private Set<Address> addresses = new HashSet<Address>();
    ...
}

Spring Data MongoDB Mapping Annotations

AnnotationDescription
@IdDetermines the identifier property. If not explicitly used, properties named id or _id are considered IDs.
@DocumentMarks a class as a document and is used to build mapping metadata during startup.
@DBRefDefines an object to be stored in a separate collection instead of being embedded.
@TransientExcludes a property from being persisted.
@IndexedDefines an index to be created for the property.
@CompoundIndexDefines a compound index to be created.
@GeoSpatialIndexedDefines a geo-spatial index for a property.
@PersistenceConstructorSelects a constructor to use for object instantiation on reads.
@ValueAllows customization of the value used for a constructor parameter.
@FieldAllows customization of the field name and field ordering in the resulting document.

Spring Data Neo4j Mapping Annotations

AnnotationDescription
@GraphIdDetermines the identifier property of a class.
@TransientExcludes a property from being persisted.
@NodeEntityDeclares an entity class to be backed by a node.
@RelationshipEntityDeclares an entity class to be backed by a relationship.
@StartNode / @EndNodeDefines the start or end node of a relationship entity.
@RelatedTo / @RelatedToViaAnnotations for entity fields that relate to other entities via relationships.
@IndexedConfigures indexing for the annotated property.

Template APIs

The Spring Data template classes have three major responsibilities: transparent object-to-store mapping, resource management, and exception translation into Spring's DataAccessException hierarchy. fileciteturn4file0L262-L287

#Responsibility
1Transparent integration of object-to-store mapping.
2Reliable resource acquisition and release, including when exceptions are thrown.
3Translate persistence-specific exceptions into Spring's DataAccessException hierarchy.

Template method groups

GroupExamples / Purpose
Standard use casesfindOne(...), findAll(...)
Store-specific functionsMongoDB: createCollection(...), geoNear(...); Neo4j: createNode(...), traverse(...)
Low-level callbacksexecute(...) methods provide native API access while retaining resource management and exception translation.

Repositories & Query Customization

Spring Data uses an interface-based programming model to reduce repetitive repository boilerplate. fileciteturn4file0L288-L302

CustomerRepository

interface CustomerRepository extends Repository<Customer, Long> {
    Customer findByEmailAddress(EmailAddress email);
    List<Customer> findByAddressCity(String city);
    Page<Customer> findByLastnameLike(String lastname, Pageable pageable);
}

The source explains that method names are parsed into store-specific queries and that the query is created during application bootstrap. fileciteturn4file0L309-L355

Customizing Query Execution with @Query

interface CustomerRepository extends Repository<Customer, Long> {
    @Query("select c from Customer c where c.emailAddress = ?1")
    Customer findByEmailAddress(EmailAddress email);
}

The source also describes JPA named queries and store-named query properties files as alternatives for keeping queries outside the repository interface. fileciteturn4file0L375-L389

Repository Base Interfaces

Base interfaceDescription
RepositoryMarker interface to communicate the domain and ID types to the infrastructure.
CrudRepositoryExposes CRUD (Create, Read, Update, Delete) methods for the configured domain type. Extends Repository.
PagingAndSortingRepositoryExtends CrudRepository and exposes sorting and paginated lookup methods.
JpaRepository, MongoDbRepository, Neo4jRepositoryUsually extend from PagingAndSortingRepository and provide additional store-specific methods.

The refcard recommends avoiding store-specific interfaces when possible because they reveal persistence technology to the client and couple the code to it. fileciteturn4file0L390-L413

Pagination & Sorting

PagingAndSortingRepository captures sorting and page-by-page access through Sort, Pageable, and Page. fileciteturn4file0L414-L445

// Create request for the 2nd page by a page size of 10
Sort sort = new Sort(Direction.ASC, "lastname", "firstname");
Pageable pageable = new PageRequest(1, 10, sort);
Page<Customer> customers = repository.findAll(pageable);

assertThat(customers.isFirstPage(), is(false));
assertThat(customers.hasNextPage(), is(true));

for (Customer customer : customers) {
    // ... do something with the Customer
}

Request Parameters

ParameterDescription
pagePage number, 0-indexed; defaults to 0.
sizePage size; defaults to 20.
sortComma-separated field references followed by asc/desc. Example: /?sort=firstname,asc&lastname=desc.

Customization Annotations

AnnotationDescription
@QualifierDefines a qualifier when multiple pages or sorts are passed to a single method.
@PageableDefaultCustomizes defaults for Pageable when no request parameters are present.
@SortDefaultCustomizes defaults for Sort when no request parameters are present.

Querydsl & Advanced Features

Querydsl

Querydsl brings LINQ-style query capabilities to Java. It is centered around a meta-model generated from domain classes, which can define predicates executed through a Spring Data repository. fileciteturn4file0L446-L490

Maven Meta-model Generation

<plugin>
    <groupId>com.mysema.maven</groupId>
    <artifactId>apt-maven-plugin</artifactId>
    <version>1.0.9</version>
    <executions>
        <execution>
            <goals>
                <goal>process</goal>
            </goals>
            <configuration>
                <outputDirectory>
                    target/generated-sources/java
                </outputDirectory>
                <processor>
                    com.mysema.query.apt.jpa.JPAAnnotationProcessor
                </processor>
            </configuration>
        </execution>
    </executions>
</plugin>

Predicate Definition

QCustomer customer = Qcustomer.customer;
Predicate predicate = customer.lastname.endswith(...).
    or(customer.firstname.startsWith(...));

Predicate Execution

interface CustomerRepository extends Repository<Customer, Long>,
        QueryDslPredicateExecutor<Customer, Long> {
}

CDI Integration

The source describes four steps: include the necessary Spring Data JARs, declare infrastructure components as CDI beans, declare repositories, and inject repository instances with @Inject. fileciteturn4file0L510-L519

Spring & SpringMVC Integration

Base interface / support typeDescription
DomainClassConverterConverts a String ID into the entity using the repository registered for the domain type.
DomainClassPropertyEditorLegacy version of DomainClassConverter.
SortHandlerMethodArgumentResolverAutomatically creates a Sort instance from HttpServletRequest parameters.
PageableHandlerMethodArgumentResolverAutomatically creates a Pageable instance from HttpServletRequest parameters.

DomainClassConverter Example

@Controller
public class CustomerController {
    @RequestMapping("/customers/{id}")
    public String showUserForm(
        @PathVariable("id") Customer customer, Model model) {
        ...
    }
}

Pagination Argument Resolvers

class WebConfiguration extends WebMvcConfigurationSupport {
    protected void addArgumentResolvers(
        List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new SortHandlerMethodArgumentResolver());
        resolvers.add(new PageableHandlerMethodArgumentResolver());
    }
}

The source also shows a controller accepting a Pageable argument and using repository.findAll(pageable). fileciteturn4file0L652-L685

Spring Data REST & Resources

Spring Data REST automatically exports repository-managed entities in a hypermedia-driven way, rendering customizable JSON representations and providing extension/customization hooks for validation, security and integration. fileciteturn4file0L686-L700

ResourceReference from source
Spring Data RESTProject information is referenced in the supplied refcard.
Spring Data projectProject home is referenced in the supplied refcard.

Query Derivation & Store-Specific Queries

The repository infrastructure parses query method names into store-specific queries. The refcard lists logical keywords including AFTER, BEFORE, BETWEEN, CONTAINING, ENDING_WITH, EXISTS, GREATER_THAN, IN, IS, NULL checks, LESS_THAN, LIKE, NOT, STARTING_WITH, TRUE, NEAR, WITHIN and REGEX. fileciteturn4file0L309-L364

Logical KeywordKeyword Expressions
AFTERAfter, IsAfter
BEFOREBefore, IsBefore
BETWEENBetween, IsBetween
CONTAININGContaining, IsContaining, Contains
ENDING_WITHEndingWith, IsEndingWith, EndsWith
EXISTSExists
FALSEFalse
GREATER_THANGreaterThan, IsGreaterThan
GREATER_THAN_EQUALSGreaterThanEqual, IsGreaterThanEqual
INIn, IsIn
ISIs, Equals, or no keyword
IS_NOT_NULLNotNull, IsNotNull
IS_NULLNull, IsNull
LESS_THANLessThan, IsLessThan
LESS_THAN_GREATERLessThanGreater, IsLessThanGreater
LIKELike, IsLike
NOTNot, IsNot
NOT_INNotIn, IsNotIn
NOT_LIKENotLike, IsNotLike
STARTING_WITHStartingWith, IsStartingWith, StartsWith
TRUETrue, IsTrue
NEARNear, IsNear
WITHINWithin, IsWithin
REGEXRegex, MatchesRegex, Matches

Example Store Queries

StoreQuery expression
JPASelect c from Customer c where c.address.city = ?1
MongoDB{ "address.city" : ?0 }
Neo4jstart address=node:Address(city={0}) match address<-[:LIVES_AT]-customer return customer

Original PDF Pages

The original seven pages are preserved below. Pages 2–6 contain the main Core Spring Data material, while the surrounding pages include the refcard cover and publication/resources material.

Original Page 1 Original Core Spring Data PDF page 1
Original Page 2 Original Core Spring Data PDF page 2
Original Page 3 Original Core Spring Data PDF page 3
Original Page 4 Original Core Spring Data PDF page 4
Original Page 5 Original Core Spring Data PDF page 5
Original Page 6 Original Core Spring Data PDF page 6
Original Page 7 Original Core Spring Data PDF page 7