Data plays a crucial role in today’s world; from accessing, persisting, and analyzing it, to effectively using the information for better results.
In our previous article, we have created our first Spring Boot application. Through this article, we will look at how Spring Data MongoDB makes, work simple when it comes to Data Modeling. It makes it easy to use non-relational databases with web applications.
Spring Data MongoDB
Spring Data JPA (Java Persistence API) is a good choice for relational databases; on the other hand, Spring data MongoDB is making data modeling easy for non-relational databases. MongoDB is a document-based no-SQL database. Let’s see how to make an application to store and retrieve data using Spring Data MongoDB.
Adding MongoDB Dependency
To use MongoDB, one has to add below dependency in the pom.xml
file and update the maven
configuration.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> |
If you are using an Eclipse IDE, you can update the same by running the below command from the command prompt.
mvn eclipse:eclipse
Create an Entity
MongoDB is a collection-based document. Hence, to store data we need to create an entity similar to our table. Every mongo data model should have an id with @Id
annotation. This will be the primary key of our collection in a document.
A data model can be created as follows,
// UserData.java package application.model.data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; public class UserData { @Id public String id; @Indexed(unique = true) public String userId; public String userName; public String userAge; }
MongoRepository
interface
Spring Data MongoDB inherits the querying functionality from the spring data common object. So, we need not worry about MongoDB query language. We have a handful of methods that will query us.
MongoRepository
is an interface that comes with standard CRUD (Create, Read, Update and Delete) operation.
We can create UserRepository
extending MongoRepository
with @Repository
annotation as follows;
// UserDataRepository.Java package application.repo.data; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import application.model.data.UserData; @Repository public interface UserDataRepository extends MongoRepository<UserData, String> { }
Note : (If you want to override default MongoRepository operations, you can create a concrete implementation of the above interface)
Establish MongoDB Connection
By default, Spring Boot tries to establish a connection with local instance of MongoDB. So, if you are having MongoDB in local, then no need to worry about making it configurable with spring boot project. Instead, spring boot will work for us. For the advance configuration we have to use application.properties
as follows;
- spring.data.mongodb.authentication-database=#Authentication
- spring.data.mongodb.database=#DB name
- spring.data.mongodb.host=#Host.
- spring.data.mongodb.username= #User.
- spring.data.mongodb.password=#Password
- spring.data.mongodb.port=#Port
- spring.data.mongodb.uri=#When set, host and port are ignored.
Creating RESTful API
To make our project a RESTful service; create UserDataController
with @RestController
annotation. Here, we are going to auto-wire UserDataRepository
to read, write and delete data in the Databases from the client-side.
The controller can be created as follows;
// UserDataController.java package application.controller.data; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import application.model.data.UserData; import application.repo.data.UserDataRepository; @RestController @RequestMapping("/userdata") public class UserDataController { @Autowired private UserDataRepository repository; @PostMapping("add") public String add(@RequestBody UserData user){ try { repository.save(user); return "SUCCESS"; }catch(Exception e) { return "ERROR"; } }
The repository has a handful of methods to make CRUD operations such as create, read, update, and delete queries.
Spring Main Application class
As seen in the last chapter, spring boot starts from spring main application class.SpringBootApplication
annotation has component scan and auto-configuration by default. Since it has MongoDB driver in the classpath (By adding spring-boot-starter-data-mongodb in the pom file), based on the spring auto-configuration feature, it will automatically open the connection with MongoDB.
The main class application can be created as follows,
package application; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Note: Our Mongo Repository should be parallel to application or sub-packages of application folder so that it will be scanned by spring container otherwise we have to mention like @EnableMongoRepositories(basePackages = "application.repo")
above the MyApplication application to route bean creation.
Ready to Run the project
So that’s it. Run the application by giving the below command in a project directory,
mvn spring-boot:run |
Now it will start the webserver and since MongoDB dependency is in the classpath, it will auto configure and make connections with local MongoDB, you can confirm this by viewing the same after running the above command as follows,
If everything is fine, you will see the above result; and observe that the webserver started successfully.
Create Request to RESt Service
Now it’s time to send a request to our RESt service. So, that we can insert, read and delete data from the database.
Insert the Data
A new data can be added using PostMapping method – “add”
@PostMapping("add") public String add(@RequestBody UserData user) { try { repository.save(user); return "SUCCESS"; } catch (Exception e) { return "ERROR"; } }
By making the request to our rest controller, we can insert the data in our database as follows,
curl -i -X POST -H "Content-Type:application/json" -d '{"userId":"john567","userName":"John" , "userAge":"21"}' http://localhost:8080/userdata/add curl -i -X POST -H "Content-Type:application/json" -d '{"userId":"harry345","userName":"Harry" , "userAge":"27"}' http://localhost:8080/userdata/add
Run above curl
in command prompt, as below;
By default, Spring Boot automatically will create the “test” as a MongoDB database name. If everything is okay, you can see the inserted data in MongoDB GUI, Compass as follows;
Note: Since we have used the save method in the MongoRepository, it will create an ID field itself and insert it into DB, if we don’t provide the same as an input.
Find All and Delete All data
PostMapping
methods for CURD operations findAll
and deleteAll
are as follows;
@PostMapping("getAll") public Map < String, Object > findAll() { Map < String, Object > response = new HashMap < String, Object > (); try { List < UserData > allList = repository.findAll(); response.put("result", allList); response.put("status", "SUCCESS"); } catch (Exception e) { response.put("status", "ERROR"); } return response; }
@PostMapping("deleteAll") public String deleteAll() { try { repository.deleteAll(); return "SUCCESS"; } catch (Exception e) { return "ERROR"; } }
By making the below request, we can getAll
Data from the database is as follows;
curl -i -X POST http://localhost:8080/userdata/getAll
The Output would be;
By making the below request, we can delete all data from the database as follows,
curl -i -X POST http://localhost:8080/userdata/deleteAll
The result would be;
To confirm the result with DB itself, we can refresh our compass GUI, to verify whether all the data from the database was removed.
So that’s it. We have worked with data and did some CRUD operations like insert, read, and delete functions.
Finally, you can stop the server by; pressing Ctrl + C keys from the keyboard from the server command prompt; or by typing the below command;
mvn spring-boot:stop |
To summarize what we have discussed;
- Performed some CRUD operations on data using the spring boot application.
- MongoRepository makes our work easier even without learning MongoDB query language.
- Spring boot auto-configuration plays a vital role when it comes to creating connections for MongoDB.
I am closing the article here. Do not forget to give your feedback in the below comments section. Also, if you have any queries on the above code, post them in the below comments section.