Over a million developers have joined DZone.

Spring Data Series: Spring Data in a Nutshell

This new series dives into Spring Data. The first article details what Spring Data is and how it and its repositories can be used.

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

In this series, we will deep dive into the Spring Data architecture. In this article, we will concentrate on the features of Spring Data and what it has to offer.

Why Spring Data?

Spring Data is an umbrella that takes care of SQL and NoSQL databases and reduces the effort to use them. The Spring community’s motto is to reduce boilerplate code, so the community invented Spring Data, which is taken one step forward than the database template. In a JPA template, although Spring hides the creation EntityManagerFactory managing Entity manager but the problem is we still have to maintain a DAO layer and provide CRUD operations for each entity. CRUD operations are similar in nature you have framed it in your mind but still, have to write or copy and paste same code over and over for different Entities.

Spring address this problem and introduce Spring data which says you don’t have to write redundant code for CRUD just define an interface, Spring creates the actual implementation on the fly. Pure magic.

Spring Data Repository

Spring Data introduced the Repository concept. Repository acts like Adapter. It takes the Entity and makes the persistence layer a specific call — it may be JPA or MongoDB, etc. The beauty of Repository is we just need to create the Interface, which will extend Spring Data’s Repository marker interface. By doing so, you instruct Spring to find those interfaces, which will extend the Repository interface and add them as a Spring bean by creating a Proxy and delegate the call to actual implementation. But as developers, we don’t have to write the actual implementation — we just need to mention what methods we need Spring to take care of that by the Create and Derivation approach.

Choosing the Underlying Persistence Layer

As I said earlier, Spring Data is like an umbrella. It contains different types of persistence layers like JPA and MongoDB so, as a client, you need to instruct Spring Data which persistence layer you want to use. So Spring Data provides different Annotations for different Repositories. If you want to use JPA, just annotate your main class with @EnableJpaRepositories. If you prefer MongoDB, then it's @EnableMongoRepositories. Now Spring Data understands that you need a JPA repository or Mongo repository so it can create JPA or Mongo-specific calls. Actually, behind the scenes, Spring Data has an implementation of each Repository like SimpleJpaRepository or SimpleMongoRepository. Spring Data internally delegates the call to the actual implementation.

Different Repositories

Spring Data provides various Repository interfaces, which extend the Marker interface Repository. You can choose them based on your need. Just create a custom interface and extend one of the Repository interfaces.

Two important Repository interfaces are:

  1. CRUDRepository

  2. PagingAndSortingRepository


Use when you need to perform CRUD operation (Create,Read,Update,Delete)

public interface CrudRepository<T, ID extends Serializable>
    extends Repository<T, ID> {                                                                                                                        
    <S extends T> S save(S entity);                                                                                                                        
    T findOne(ID primaryKey);                                                                                                                        
    Iterable<T> findAll();
    Long count();                                                                                                                        
    void delete(T entity);                                                                                                                        
    boolean exists(ID primaryKey);

}    // … more functionality omitted.


Use when you want to use paging and sorting.

public interface PagingAndSortingRepository<T, ID extends Serializable> 
    extends CrudRepository<T, ID> {
    Iterable<T> findAll(Sort sort);
    Page<T> findAll(Pageable pageable);


  • We use JPA for the Repository.
  • We use a MySQL database persistence layer.

So, to introduce Spring Data in your project, the following steps are needed.

1. Add Spring Data JPA dependencies into the pom.xml.


2. Add target database driver. We use MySQL, so we add the following:


3. Create a Person Entity.

4. Create a Person table in MySQL database.

5. Create a PersonRepository, which extends CRUDRepository.

6. Put @EnableJpaRepositories over the main class.

Now run the application. Data will successfully save in the database.

The Code

As I use Spring Boot, I use database details in application.properties:

package com.example.cab;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Person {

    private Long id;
    private String name;
    private String country;
    private String gender;
    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

    public String getCountry() {
        return country;

    public void setCountry(String country) {
        this.country = country;

    public String getGender() {
        return gender;

    public void setGender(String gender) {
        this.gender = gender;

    public Long getId() {
        return id;

    public void setId(Long id) {
        this.id = id;

    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", country=" + country + ", gender=" + gender + "]";

package com.example.cab;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface PersonRepositary extends CrudRepository<Person, Long> {
    List<Person> findByCountryContains(String country);

package com.example.cab;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

public class PersonApplication {
    private static final Logger log = LoggerFactory.getLogger(PersonApplication.class);

    public CommandLineRunner demo(PersonRepositary repository) {
        Person p = new Person();
        p.setName("Samir mitra");
        log.info("Person created" + p);
        return null;

    public static void main(String[] args) {

        SpringApplication.run(PersonApplication.class, args);


Output: Person createdPerson [id=4, name=Samir mitra, country=America, gender=male]

Adding an Extra Filter Query in Interface

Sometimes you want to create a query based on a property that is not in the CRUDRepository interface. You have to provision to do so. Just declare a method in your custom interface, which must have to obey the syntax. Then, Spring Data creates the query for you on the fly.

The syntax is Queryname<java property><Operation>, like we create a query in the Person Repository — List<Person> findByCountryContains(String country);

If you run the application, the output will be:

        person0_.id as id1_0_,
        person0_.country as country2_0_,
        person0_.gender as gender3_0_,
        person0_.name as name4_0_ 
        person person0_ 
        person0_.country like ?
2016-09-24 21:37:32.334  INFO 6384 --- [           main] com.example.cab.PersonApplication        : Person Person [id=1, name=Shamik mitra, country=India, gender=male]
2016-09-24 21:37:32.334  INFO 6384 --- [           main] com.example.cab.PersonApplication        : Person Person [id=2, name=Swastika mitra, country=India, gender=Female]
2016-09-24 21:37:32.334  INFO 6384 --- [           main] com.example.cab.PersonApplication        : Person Person [id=3, name=Swastika mitra, country=India, gender=Female]

Delete Operation

When the discussion comes to deletion, a curious mind often asks, "Does Spring Data support soft deletes?" The answer is no. Spring Data only supports physical deletes as of now.

Use a Handcrafted Query

If you want, you can use your handcrafted query with the @Query interface. One use case may be that you don’t want a physical delete, so you override the Spring Data query with your handcrafted soft delete query.

Just redefine the method, add @Query, and pass the query.

@Query("select p from Person p where p.country like ?1")
List<Person> findByCountryContains(String country);

Query DSL

When you search an entity by its properties in Spring Data, you declare them in the interface. But what if you want to create a query that will search the entity dynamically?

What Do You Do?

One approach is declaring a method in all possible combinations, but this is a bad idea. Your interface will be long and, with additions and deletions, property combinations will need to be modified.

Criteria API is the solution; we use Criteria API for the same reason. We can introduce a Predicate and query DSL for it.

Spring Data uses queries, which is quite similar to the Criteria API, but with a different approach. Just like the JPA, Criteria API uses a Java 6 annotation processor to generate meta-model objects, but it produces a much more approachable API.

To enable it, add the following plugin in pom.xml.


In the output directory, it creates a special class — QPerson. Using QPerson.person, we can access every property and build our query.

Benefits of Spring Data

  1. Get rid of boilerplate DAO classes.

  2. Easily switch from repository one to another.

  3. You don’t have to be an expert in JPA or Mongo queries. Spring will take care of it in an optimized way.

  4. Highly flexible and support to add your own custom queries.

From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.

spring data jpa,spring data,java,crud

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}