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. fileciteturn4file0L81-L103
| Store | XML element / feature | Description |
|---|---|---|
| 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. fileciteturn4file0L167-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
| Annotation | Description |
|---|---|
@Id | Determines the identifier property. If not explicitly used, properties named id or _id are considered IDs. |
@Document | Marks a class as a document and is used to build mapping metadata during startup. |
@DBRef | Defines an object to be stored in a separate collection instead of being embedded. |
@Transient | Excludes a property from being persisted. |
@Indexed | Defines an index to be created for the property. |
@CompoundIndex | Defines a compound index to be created. |
@GeoSpatialIndexed | Defines a geo-spatial index for a property. |
@PersistenceConstructor | Selects a constructor to use for object instantiation on reads. |
@Value | Allows customization of the value used for a constructor parameter. |
@Field | Allows customization of the field name and field ordering in the resulting document. |
Spring Data Neo4j Mapping Annotations
| Annotation | Description |
|---|---|
@GraphId | Determines the identifier property of a class. |
@Transient | Excludes a property from being persisted. |
@NodeEntity | Declares an entity class to be backed by a node. |
@RelationshipEntity | Declares an entity class to be backed by a relationship. |
@StartNode / @EndNode | Defines the start or end node of a relationship entity. |
@RelatedTo / @RelatedToVia | Annotations for entity fields that relate to other entities via relationships. |
@Indexed | Configures 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. fileciteturn4file0L262-L287
| # | Responsibility |
|---|---|
| 1 | Transparent integration of object-to-store mapping. |
| 2 | Reliable resource acquisition and release, including when exceptions are thrown. |
| 3 | Translate persistence-specific exceptions into Spring's DataAccessException hierarchy. |
Template method groups
| Group | Examples / Purpose |
|---|---|
| Standard use cases | findOne(...), findAll(...) |
| Store-specific functions | MongoDB: createCollection(...), geoNear(...); Neo4j: createNode(...), traverse(...) |
| Low-level callbacks | execute(...) 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. fileciteturn4file0L288-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. fileciteturn4file0L309-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. fileciteturn4file0L375-L389
Repository Base Interfaces
| Base interface | Description |
|---|---|
Repository | Marker interface to communicate the domain and ID types to the infrastructure. |
CrudRepository | Exposes CRUD (Create, Read, Update, Delete) methods for the configured domain type. Extends Repository. |
PagingAndSortingRepository | Extends CrudRepository and exposes sorting and paginated lookup methods. |
JpaRepository, MongoDbRepository, Neo4jRepository | Usually 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. fileciteturn4file0L390-L413
Pagination & Sorting
PagingAndSortingRepository captures sorting and page-by-page access through Sort, Pageable, and Page. fileciteturn4file0L414-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
| Parameter | Description |
|---|---|
page | Page number, 0-indexed; defaults to 0. |
size | Page size; defaults to 20. |
sort | Comma-separated field references followed by asc/desc. Example: /?sort=firstname,asc&lastname=desc. |
Customization Annotations
| Annotation | Description |
|---|---|
@Qualifier | Defines a qualifier when multiple pages or sorts are passed to a single method. |
@PageableDefault | Customizes defaults for Pageable when no request parameters are present. |
@SortDefault | Customizes 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. fileciteturn4file0L446-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. fileciteturn4file0L510-L519
Spring & SpringMVC Integration
| Base interface / support type | Description |
|---|---|
| DomainClassConverter | Converts a String ID into the entity using the repository registered for the domain type. |
| DomainClassPropertyEditor | Legacy version of DomainClassConverter. |
| SortHandlerMethodArgumentResolver | Automatically creates a Sort instance from HttpServletRequest parameters. |
| PageableHandlerMethodArgumentResolver | Automatically 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). fileciteturn4file0L652-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. fileciteturn4file0L686-L700
| Resource | Reference from source |
|---|---|
| Spring Data REST | Project information is referenced in the supplied refcard. |
| Spring Data project | Project 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. fileciteturn4file0L309-L364
| Logical Keyword | Keyword Expressions |
|---|---|
AFTER | After, IsAfter |
BEFORE | Before, IsBefore |
BETWEEN | Between, IsBetween |
CONTAINING | Containing, IsContaining, Contains |
ENDING_WITH | EndingWith, IsEndingWith, EndsWith |
EXISTS | Exists |
FALSE | False |
GREATER_THAN | GreaterThan, IsGreaterThan |
GREATER_THAN_EQUALS | GreaterThanEqual, IsGreaterThanEqual |
IN | In, IsIn |
IS | Is, Equals, or no keyword |
IS_NOT_NULL | NotNull, IsNotNull |
IS_NULL | Null, IsNull |
LESS_THAN | LessThan, IsLessThan |
LESS_THAN_GREATER | LessThanGreater, IsLessThanGreater |
LIKE | Like, IsLike |
NOT | Not, IsNot |
NOT_IN | NotIn, IsNotIn |
NOT_LIKE | NotLike, IsNotLike |
STARTING_WITH | StartingWith, IsStartingWith, StartsWith |
TRUE | True, IsTrue |
NEAR | Near, IsNear |
WITHIN | Within, IsWithin |
REGEX | Regex, MatchesRegex, Matches |
Example Store Queries
| Store | Query expression |
|---|---|
| JPA | Select c from Customer c where c.address.city = ?1 |
| MongoDB | { "address.city" : ?0 } |
| Neo4j | start 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.