MongoDB With Spring Boot: A Simple CRUD
In this blog, we are going to explore MongoDB with Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.
Join the DZone community and get the full member experience.
Join For FreeMongoDB is an open-source non relational, document oriented database. MongoDB being document oriented means that it stores data in JSON like documents which makes it more powerful and expressive. MongoDB’s ability to scale up and down very easily is considered to be one of its advantages over its competitors. Data is stored in documents in key pair values. Another component of MongoDB is collection, which is the simple collection of documents. Collection corresponds to Table in relational databases. In this blog we are going to explore this database with Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.
Why Use MongoDB?
- It is document based and therefore it is more flexible where each document can have varying fields which can not be done in relational databases.
- It allows us to index any field in the document to improve search results.
- It provides us with rich and powerful query language which allows us to filter and sort using any field no matter how nested the field is.
- It provides us with high scalability (sharding) and high availability (replication) of data.
MongoDB With Java Spring Boot
Assuming that you have a basic understanding of MongoDB now we will now see how we can leverage MongoDB by building a small spring boot API to perform basic CRUD operations.
Prerequisites
- You should have MongoDB installed in your local environment. To save yourself some time setting it up you can also use a MongoDB Docker image, you can see how to do it here. This application will run in the default mongo port.
- Create a Spring Boot application with web-started and mongo dependencies. You can match your pom.xml with the one provided on the project repository.
Project Structure
Model
This package will have the java object model for the document. We have created a simple Person model here with fields id
and name
.
The @Document
annotation is used to define the name of the collection in which your document will be saved.
collection = "Person") (
public class Person {
private String id;
private String name;
public Person( ("id") String id,
"name") String name) { (
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
DAO
DAO in our project is the data access object. It contains the implementation for the Mongo repository.
Here, we have created an Interface PersonRepository
which extends the MongoRepository
Interface. MongoRepository
comes with basic CRUD operations for us to use out of the box. Making our task easier.
The implementation of the PersonRepository
is in the PersonDao
class. All these operations will be done using API.
Inserting Data (Create)
Here, insert()
method will take Person object as parameter and insert the person details into MongoDB.
xxxxxxxxxx
public Person insertPersonData(Person person) {
return personRepository.insert(person);
}
Getting Data (Read)
Here, we have defined two methods for reading data from MongoDB.
- For getting all person information:
getAllPersonInformation()
It will return a collection of Person
.
xxxxxxxxxx
public Collection<Person> getAllPersonInformation() {
return personRepository.findAll();
}
- For getting information of a specific person:
getPersonById()
This method will take id
as a parameter and return the person information matching the ID.
xxxxxxxxxx
public Optional<Person> getPersonInformationById(String id) {
return personRepository.findById(id);
}
Updating Existing Data
Here, updatePersonUsingId()
method will take the id and the person object as parameters.
xxxxxxxxxx
public Person updatePersonUsingId(String id, Person person) {
Optional<Person> findPersonQuery = personRepository.findById(id);
Person personValues = findPersonQuery.get();
personValues.setId(person.getId());
personValues.setName(person.getName());
return personRepository.save(personValues);
}
Deleting Data
Here, the method deletePersonUsingId()
will take an id
as a parameter and delete the person data corresponding to the ID.
xxxxxxxxxx
public void deletePersonUsingId(String id) {
try {
personRepository.deleteById(id);
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
This is it. All these operations can be done by using the API we have given in the controller. Test this application using the Postman.
Conclusion
This is just a basic CRUD example for a quick walk through but production level code is more crisp, detailed and contains many scenarios. This example is no where near that.
The link for this project is given below and contains a docker-compose.yml with MongoDB image to help you run this example quickly!
Link to Github repository for the project is here.
Opinions expressed by DZone contributors are their own.
Comments