Introduction to Spring Data - Spring Data JPA, Spring Data REST and MongoDB



This guide will help you understand the basics of Spring Data. We will look at the various options that Spring Data provides and a couple of examples - Spring Data JPA and Spring Data Mongodb.

You will learn

  • Basics of Spring Data
  • Why is Spring Data needed?
  • What are the different interfaces provided by Spring Data?
  • How to get started with Spring Data?

Free Courses - Learn in 10 Steps

What is Spring Data?

Think about the evolution of databases in the last few years.

When Spring Framework was created, in early 2000s, the only kind of database was relational database - Oracle, MS SQL Server, My SQL etc. In the last few years, there are a wide variety of databases that are getting popular - most of them not relational and not using SQL. Wide variety of terminology is used to refer to these databases. NoSQL, for example.

ORM frameworks (Hibernate) and specifications(JPA) were good fit for the relational databases. But, the newer databases, have different needs.


Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store. It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services.

To make it simpler, Spring Data provides Abstractions (interfaces) you can use irrespective of underlying data source.

Spring Data Commons

Spring Data Commons provides all the common abstractions that enable you to connect with different data stores.

Crud Repository

The key interface in Spring Data Commons is CrudRepository. It provides generic CRUD operations irrespective of the underlying data store. It extends Repository which is the base class for all the repositories providing access to data stores.

All the methods in the CrudRepository interface are shown below

public interface CrudRepository<T, ID> extends Repository<T, ID> {
	<S extends T> S save(S entity);

	<S extends T> Iterable<S> saveAll(Iterable<S> entities);

	Optional<T> findById(ID id);

	boolean existsById(ID id);

	Iterable<T> findAll();

	Iterable<T> findAllById(Iterable<ID> ids);

	long count();

	void deleteById(ID id);

	void delete(T entity);

	void deleteAll(Iterable<? extends T> entities);

	void deleteAll();

The methods in the CrudRepository are self explanatory.


The other important interface in Spring Data is PagingAndSortingRepository. PagingAndSortingRepository provides options to

  • Sort your data using Sort interface
  • Paginate your data using Pageable interface, which provides methods for pagination - getPageNumber(), getPageSize(), next(), previousOrFirst() etc.

public abstract interface PagingAndSortingRepository extends CrudRepository {

public Iterable findAll(Sort sort);

public Page findAll(Pageable pageable);


Defining Custom Repositories

You can create a custom repository extending any of the repository classes - Repository, PagingAndSortingRepository or CrudRepository.

An example is shown below

interface PersonRepository extends CrudRepository<User, Long> {

Defining custom queries

Spring Data also provides the feature of query creation from interface method names.

Look at the example below:

  List<Person> findByFirstNameAndLastname(String firstName, String lastname);

Above method helps you search a data store by passing in the first name and last name of a person. This would generate the appropriate query for the data store to return the person details.

You can find more details in the spring data documentation -

Auditing with Spring Data

Spring Data also provides auditing capabilities through simple annotations.

class Student {

  private User createdUser;

  private DateTime createdDate;

  // … further properties omitted

There are corresponding annotations for updates as well

  • LastModifiedBy
  • LastModifiedDate

Spring Data Implementations

There are Spring Data Modules specific to the data store you would want to use.

  • Spring Data JPA - Connect to relational databases using ORM frameworks.
  • Spring Data MongoDB - Repositories for MongoDB.
  • Spring Data REST - Exposes HATEOAS RESTful resources around Spring Data repositories.
  • Spring Data Redis - Repositories for Redis.

Spring Data JPA

Spring Data JPA helps you to connect to relational databases using ORM frameworks.

The dependency is shown below:


The default JPA implementation used is Hibernate.

The core interface is the JpaRepository.

public interface JpaRepository<T, ID> 
	extends PagingAndSortingRepository<T, ID>, 

Some of the additional methods it provides (compared to PagingAndSortingRepository) are shown below. As you can see, all these methods are specific to JPA.

 * Saves an entity and flushes changes instantly.
 * @param entity
 * @return the saved entity
<S extends T> S saveAndFlush(S entity);

 * Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear
 * the {@link javax.persistence.EntityManager} after the call.
 * @param entities
void deleteInBatch(Iterable<T> entities);

 * Deletes all entities in a batch call.
void deleteAllInBatch();

Recommended Reading for Spring Data JPA -

Spring Data REST

Spring Data REST can be used to expose HATEOAS RESTful resources around Spring Data repositories.

An example using JPA is shown below

@RepositoryRestResource(collectionResourceRel = "todos", path = "todos")
public interface TodoRepository
		extends PagingAndSortingRepository<Todo, Long> {

A few example REST Services are shown below:


  • URL : http://localhost:8080/todos
  • Use Header : Content-Type:application/json

Request Content

  "user": "Jill",
  "desc": "Learn Hibernate",
  "done": false

Response Content

  "user": "Jill",
  "desc": "Learn Hibernate",
  "done": false,
  "_links": {
    "self": {
      "href": "http://localhost:8080/todos/1"
    "todo": {
      "href": "http://localhost:8080/todos/1"

The response contains the href of the newly created resource.


  • URI - http://localhost:8080/todos


  "_embedded" : {
    "todos" : [ {
      "user" : "Jill",
      "desc" : "Learn Hibernate",
      "done" : false,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/todos/1"
        "todo" : {
          "href" : "http://localhost:8080/todos/1"
    } ]
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/todos"
    "profile" : {
      "href" : "http://localhost:8080/profile/todos"
    "search" : {
      "href" : "http://localhost:8080/todos/search"
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0

GET to http://localhost:8080/todos/1

  "user" : "Jill",
  "desc" : "Learn Hibernate",
  "done" : false,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/todos/1"
    "todo" : {
      "href" : "http://localhost:8080/todos/1"

Spring Data Rest also supports search using column names

  • Example - http://localhost:8080/todos?user=Jill

Spring Data Rest can be extended by defining custom methods in the repositories. http://localhost:8080/todos/search/findByUser?user=Jill can be used expose specific search method defined below.

@RepositoryRestResource(collectionResourceRel = "todos", path = "todos")
public interface TodoRepository
		extends PagingAndSortingRepository<Todo, Long> {

	List<Todo> findByUser(@Param("user") String user);


Spring Data REST supports

  • Spring Data JPA
  • Spring Data MongoDB
  • Spring Data Neo4j
  • Spring Data GemFire
  • Spring Data Cassandra

Recommended Reading for Spring Data Rest -

Spring Data MongoDB

Spring Data MongoDB provides support for using MongoDB as data store.

The key interface is MongoRepository.

public interface MongoRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> 

Some of the important methods (provided in addition to PagingAndSortingRepository) are shown below. You can see examples of search by example.

	 * (non-Javadoc)
	 * @see
	<S extends T> List<S> findAll(Example<S> example);

	 * (non-Javadoc)
	 * @see,
	<S extends T> List<S> findAll(Example<S> example, Sort sort);

8 AWS Certification Courses

We are releasing courses for 3 Certifications under 3 categories - STEP BY STEP, EXAM REVIEW and PRACTICE TESTS:

  • Step by Step courses are for you if you are getting started with AWS
  • Exam Review courses help you to quickly review for the exam in a few hours
  • Practice Tests help you to test your preparation - How ready are you for the exam?


EXAM REVIEW COURSES: You prepare for the exam for 1-6 months. How do you remember everything you studied? Review for the exam in under 6 HOURS using this crash courses!

PRACTICE TESTS: Test yourselves for the certification exam with our practice tests

Best Selling Udemy Courses

Image Image Image Image Image Image Image Image Image Image Image

Join 450,000 Learners and 30+ Amazing Courses

350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure

Do not know where to start your learning journey? Check out our amazing learning paths:
Learning Path 01 - Spring and Spring Boot Web Applications and API Developer,
Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular,
Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes,
Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and
Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes



Related Posts

Understanding jwt token

Let us understand the json web tokens

Single sign-on workflow

Let us understand the single sign-on workflow

Oauth2.0 - Resource Owner Password Credentials grant workflow

Let us understand the Oauth2.0 Resource Owner Password Credentials grant workflow

Oauth2.0 - Implicit grant workflow

Let us understand the Oauth2.0 implicit grant workflow

Oauth2.0 - Client Credentials grant workflow

Let us understand the Oauth2.0 client credentials grant workflow

Oauth2.0 - Authorization grant workflow

Let us understand the Oauth2.0 authorization grant workflow

Writing Integration Tests for Rest Services with Spring Boot

Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests!

Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC

Learn using Spring Boot Starter JDBC to connect Spring Boot to H2 (in memory database) using Spring JDBC. You will create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will learn to implement the basic CRUD methods.

JUnit Tutorial for Beginners in 5 Steps

JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit.

JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2

JPA and Hibernate in 10 Steps with H2 - Setting up a basic project example with Spring Boot and in memory database H2. Its a cake walk.