Spring Data Initial Concept
A brief discussion on the Initial Concept of Spring Data is described in this springcavaj – Spring Data page with an architecture diagram.
This guide will provide an understanding of Spring Data to build an application that stores and retrieves data using Mongo DB as the underlying database.
Advantage of using Spring Data with Mongo
- No-code Repositories – One of the most popular persistence-related patterns is the Repository Pattern. It helps the developer to only focus on the implementation of business logic and hides the data store specific implementation details.
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SpringDataRestRepository extends MongoRepository<User, String>
Here, you can see that I have used MongoRepository to perform the CRUD operations on the entity – User. Because in this example, I have used MongoDB as the underlying database. MongoRepository extends PagingAndSortingRepository and QueryByExampleExecutor . By this implementation you will get the default implementations of methods like:
- To insert, update and delete one or more User
- To find one or more User by their primary keys
- To count, get and delete all Users
- To check if a User with a given primary key already exists or not
- Reduce boilerplate code – Spring-Data provides a default implementation for each method like read or write operations.
- Generated Queries – Spring-Data generates the database queries based on their method names. You just need to define a method in your repository interface with a name that starts with findBy.
@Repository
public interface SpringDataRestRepository extends MongoRepository<User, String> {
public List<User> findByFirstName(String firstName);
public List<User> findByLastName(String lastName);
public User findByMobileNo(String mobileNo);
public User findByEmail(String email);
public User findByPanNo(String panNo);
}
Here you can see that this Repository Interface extends MongoRepository and I have attached the User entity in the concept of Generics as the 1st argument and in the 2nd argument provide the data type of the Primary Key as defined in the entity. In my case the data type of the primary key used in User entity is String.
Using Spring Data with Spring Boot and use MongoDB as database
We can say now that the introduction of Spring-Data makes the implementation of persistent layer much easier to a developer. For this let’s make our hands dirty by creating a project. I have created a Demo project named as spring-data-mongo-masterclass uploaded in my personal GitHub account. One can clone the project and can test locally in their system. All the steps that are required to download the project from GitHub and running it locally are mentioned in the README.md file of spring-data-mongo-masterclass repository.
- Brief Description – I have developed a project named as spring-data-masterclass using Spring Boot, Maven, Java and Mongo as underlying database. In this project I mainly focus on implementing the Spring-data with Spring-REST service. It consists of a Controller annotated with @RestController annotation, a Repository extending the MongoRepository and the CRUD operations to the Mongo Database. To test the Services, I have used Postman.
- Software Used – Software required to develop this project.
- Spring Tool Suite-4.7.0-RELEASE – If latest version is available then download that one
- Apache Maven 3.6.3 – If latest version is available then download that one
- Java 8 – Not less than Java8
- Git 2.27.0 – Latest version as available
- Mongo 4.2.8 – Mongo DB Server
- Robo 3T 1.3.1 – Mongo DB Client to see the data as persisted in DB. You can download any other client as available in the market
- Postman v8.3.0 – To test the REST Service
- List of the above software and their download link with the installation steps are briefly described in the README.md file of spring-data-mongo-masterclass repository
- Project Components – The project that I develop in support to the spring-data with Mongo concept is a Maven project. And I have used one dependency as spring-boot-starter-data-mongodb. The reason behind this as I have used Mongo as the underlying database.
<!-- Spring Mongo Dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
In the next step I have configured the database connection in application.yml file. You can use either application.properties or application.yml file. A wonderful concept using Spring Boot and Spring Data is that they handle the default configuration for you, you only need to override the parameters you want to change.
spring:
application:
name: spring-data-mongo-crud
profiles: defualt
data:
mongodb:
uri: mongodb://localhost:27017/spring
If you use application.properties then the name of the property is spring.data.mongodb.uri=mongodb://localhost:27017/spring. I have used application.yml file so it follows the indentation level.
- Structure of the Project – To use Spring Data and its libraries in your project you need to structure it in a right way.
Spring Boot expects that all source files are located in a sub-packages of the class annotated with @SpringBootApplication. In the above sample project, I have one class named as SpringDataMongoRestApplication.java which has the @SpringBootApplication annotations in it. And it is the starting point of the application.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataMongoRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataMongoRestApplication.class, args);
}
}
- Spring-Data Implementation – To implement Spring-Data I have used one of its dependencies named spring-boot-starter-data-mongodb. For this you need to define one Model class which will interact with the database and a Repository interface which you will use for the CRUD operations with the database.
Let’s look to the Model class first named as User.java
@Document(collection = "userModel")
public class User implements Serializable {
private static final long serialVersionUID = -7707576683418425977L;
@Id
private String id;
private String firstName;
private String middleName;
private String lastName;
private String mobileNo;
private String email;
private String panNo;
Here you can see that the Model class name is User annotated with @Document(collection=”userModel”). It means that whenever you persist the User model data the name of the collection in Mongo will be userModel. In Mongo, a table is referred to as a collection. And for this collection the primary key is id as the property is annotated with @Id annotation.
Now we will explore the Repository interface
@Repository
public interface SpringDataRestRepository extends MongoRepository<User, String>{
public List<User> findByFirstName(String firstName);
public List<User> findByLastName(String lastName);
public User findByMobileNo(String mobileNo);
public User findByEmail(String email);
public User findByPanNo(String panNo);
@Query("{$and: [{firstName: ?0}, {lastName: ?1}]}")
public User findByFirstAndLastName(String firstName, String lastName);
}
Here you can see that the methods are declared by following a naming convention as findBy then the name of the property as defined in the User model. And the best thing is that you don’t need to provide any implementation for this. As, spring-data itself provides that.
But if you declared a method as provided below:
public List<User> fetchByFirstName(String firstName);
When you run the application you will get the following error as:
It means that you have defined a method without following the basic spring data naming convention.
Here I have used one custom query example to find the record based on firstName and lastName. I have used one annotation as @Query(“{$and: [{firstName: ?0}, {lastName: ?1}]}”). In this project I have used @RestController and use the Spring-Rest annotations as @GetMapping, @PostMapping, @PutMapping and @DeleteMapping.This project has no UI implementation. If anyone try to integrate UI then one can clone the repository and add the UI components there.
- Testing the application – In this application there is no UI component. So, I have used Postman to test the REST endpoint as defined in the Controller class.
- You clone the application from GitHub and set up the application locally in any one of the IDEs like Spring Tool Suite (STS) or Eclipse.
- Right click on the application
- Click the Option Run As
- Select the option Spring Boot App.
- It will start the application in the port no 7111.
- Now in Postman you can test the endpoints.
Below I have provided the list of endpoints as available in this application.
- Get all Users – localhost:7111/allUsers
- Save an User – localhost:7111/saveUser, in the Body provide the JSON Object. A dummy JSON object is provided.
- Update an User – localhost:7111/updateUser/{id}, in the Body again provides the JSON data.
- Delete an User – localhost:7111/deleteUser/{id}
- Get User By First Name – localhost:7111/getUserByFirstName/{firstName}
- Get User By Last Name – localhost:7111/getUserByLastName/{lastName}
- Get User By Mobile No – localhost:7111/getUserByMobileNo/{mobileNo}
- Get User By Email – localhost:7111/getUserByEmail/{email}
- Get User By Pan No – localhost:7111/getUserByPan/{panNo}
- Get User By Name – localhost:7111/getUserByName/{firstName}/{lastName}
- Sample JSON Data – I have provided 2 sample JSON data one to insert the record in DB and another to update the same record in DB.
Insert Request – JSON Data
{
“firstName” : “First”,
“middleName” : “Middle”,
“lastName” : “Last”,
“mobileNo” : “9876543210”,
“email” : “[email protected]”,
“panNo” : “SDSDF1007M”
}
Update Request – JSON Data
{
“id” : “67893434dsejnewunqwer23213213”,
“firstName” : “First_Change”,
“middleName” : “Middle”,
“lastName” : “Last”,
“mobileNo” : “9876543210”,
“email” : “[email protected]”,
“panNo” : “SDSDF1007M”
}
GitHub Code Link
Download the Source Code from GitHub
Common Faced Problems
Interview FAQs
Other Useful Links of Spring Data
Spring Data using RDBMS (MySQL DB) and Spring REST
Spring Data using Cypher Neo4j DB and Spring REST
Spring Data using Redis and Spring REST
Other Useful Links
Spring Apache Kafka – Producer & Consumer
Spring Kafka Confluent – Set Up
Spring Kafka Confluent – Producer & Consumer
Spring Cloud using Google Cloud SQL & Google Cloud Storage