What is a Spring Boot ?
Spring Boot is an auto-configured microservice-based web framework that provides built-in features for security and database access.
If we sre using Spring boot, we can quickly create stand-alone applications without having to make too many configuration changes.
Table of Content :
- What is a Spring Boot ?
- Spring Boot Features
- What is a MongoDB ?
- Features Of MongoDB
- What is MongoTemplate?
- What is a MongoRepository?
- Create project using Spring Initializr
- Create required java classes
- Spring boot MongoDB Examples
- Questions realted to Spring Boot with MongoDB
- Summary
- Create stand-alone Spring applications
- Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files).
- Provide opinionated 'starter' dependencies to simplify your build configuration.
- Automatically configure Spring and 3rd party libraries whenever possible.
- Provide production-ready features such as metrics, health checks, and externalized configuration.
- Absolutely no code generation and no requirement for XML configuration.
- Ad-hoc queries for optimized, real-time analytics.
- Indexing appropriately for better query executions.
- Replication for better data availability and stability.
- Sharding.
- Load balancing.
Spring Boot Features
What is a MongoDB ?
MongoDB is the most popular NoSQL database because of the ease with which data can be stored and retrieved.
Combining Spring Boot and MongoDB results in applications that are fast, secure, reliable, and require minimum development time.
Features Of MongoDB
This article will see the practical introduction to Spring Data MongoDB.
We will see how to use the MongoTemplate as well as MongoRepository, with practical examples.
We will also see examples to query documents from MongoDB, by using Query, Criteria, and along with some of the common operators.
What is MongoTemplate?
The MongoTemplate class is the primary implementation of the mongo-operations interface which specifies the basic set of MongoDB operations. It implements a set of ready-to-use APIs. It offers more fine gained control over custom queries.
public class MongoTemplate
extends Object
implements MongoOperations, ApplicationContextAware, IndexOperationsProvider
What is a MongoRepository?
We can also use the MongoRepository interface to perform MongoDB operations. The implementation class of MongoRepository uses MongoTemplate bean at run time.
MongoRepository is used for basic queries that involve all or many fields of the document. Examples include data creation, viewing documents, and more.
The primary implementation of MongoOperations.
Create project using Spring Initializr
To make a quick start go to Spring Initializr and select required details like Java version dependencies,
Select Maven Project
Select Java Language
Select Spring Boot version as 3.0.0(SNAPSHOT).
Add the project metadata like Group, Artifact, Name Description, and Package Name.
Select Packaging as Jar.
Select Java Version as 17.
On the right-hand side, search and add required dependencies.
As we are creating an MVC application with MongoDB, search web and MongoDB dependencies and add the dependencies.
The project structure looks like
Create required java classes
Configuration for UserRepository
Create a new class called UserRepository.java
package com.javacodestuffs.spring.mongodb.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.javacodestuffs.spring.mongodb.dto.User;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
Create a class UserController.java, where we are handling the requests
@RestController
@RequestMapping(value = "/user")
public class UserController {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Autowired
private UserService userService;
......
Add content in application.properties
In the application.properties file, add the MongoDB connection details as below:
#Local MongoDB config
spring.data.mongodb.authentication-database=userdb
spring.data.mongodb.username=devuser
spring.data.mongodb.password=geeksandnerds
spring.data.mongodb.database=user
spring.data.mongodb.port=27017
spring.data.mongodb.host=127.0.0.1
# App config
server.port=9000
spring.application.name=Spring Boot Mongodb Example
server.context-path=/user
Using postman create request as below
http://localhost:9000/user/create
{
"fname" : "Sara",
"lname" : "Joseph",
"name" : "Sara Joseph",
"city" : "Paris",
"email" : "sara@gmail.com"
}
the equivalent CURL
request will be:
curl -X POST \
http://localhost:9000/user/create \
-H 'authorization: Basic cG9zdG1hbjpwYXNzd29yZA==' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-H 'postman-token: dc928b0e-6672-52d8-042e-6e9133f4f1b4' \
-d '{
"fname" : "Sara",
"lname" : "Joseph",
"name" : "Sara Joseph",
"city" : "Paris",
"email" : "sara@gmail.com"
}
it results in response as,
{
"userId": "631cea3ca23e7b56b156fd2c",
"name": "Sara Joseph",
"email": "sara@gmail.com",
"city": "Paris",
"fname": "Sara",
"lname": "Joseph",
"creationDate": "2022-09-10T19:49:16.367+00:00",
"revisionDateTime": "2022-09-10T19:49:16.367+00:00"
}
When we insert record, our record in the database looks like
{
"_id" : ObjectId("631cea3ca23e7b56b156fd2c"),
"name" : "Sara Joseph",
"email" : "sara@gmail.com",
"city" : "Paris",
"fname" : "Sara",
"lname" : "Joseph",
"creationDate" : ISODate("2022-09-10T19:49:16.367+0000"),
"RevisionDateTime" : ISODate("2022-09-10T19:49:16.367+0000"),
"_class" : "com.javacodestuffs.spring.mongodb.dto.User"
}
To update the existing user, we have
user = mongoTemplate.findOne(
Query.query(Criteria.where("email").is("amenda@gmail.com")), User.class);
user.setName("kelly");
mongoTemplate.save(user);
FindAndModify
This works like updateMulti, but it will returns the object before it was modified
First, we need to find the given document in MongoDB and then we modify the document as per requirement.
Query query = new Query();
query.addCriteria(Criteria.where("email").is("sara@gmail.com"));
Update update = new Update();
update.set("city", "Paris");
User user = mongoTemplate.findAndModify(query, update, User.class);
Update multiple documents at the same time
We can update multiple documents at the same time
Query query = new Query();
query.addCriteria(Criteria.where("fname").is(fname));
Update update = new Update();
update.set("lname", "Lara");
mongoTemplate.updateMulti(query, update, User.class);
return mongoTemplate.findOne(query, User.class);
Upsert
The upsert works on the find and modifies else create semantics: if the document is matched, update it, or else create a new document by combining the query and update object.
Query query = new Query();
query.addCriteria(Criteria.where("fname").is(user.getFname()));
query.addCriteria(Criteria.where("lname").is(user.getLname()));
Update update = new Update();
update.set("fname", "Sara");
update.set("lname", "Joseph");
mongoTemplate.upsert(query, update, User.class);
Remove
We'll first find the user by email in the database and then call the remove method to remove the user from MongoDB.
Query query = new Query();
query.addCriteria(Criteria.where("email").is(email));
User user = mongoTemplate.findOne(query, User.class);
DeleteResult deleteResult = mongoTemplate.remove(user, "user");
return deleteResult.getDeletedCount();
findById using UserRepositiry
We can use UserRepository as well to run mongo Queries
Optional<User> user = userRepository.findById(userId);
if (user.isPresent()) {
return user.get();
}
return new User();
Questions related to Spring Boot with MongoDB
Can we use Spring boot with MongoDB?
Yes. MongoDB and Spring Boot interact using the MongoTemplate class and MongoRepository interface. MongoTemplate — MongoTemplate implements a set of ready-to-use APIs.
Does JPA work with MongoDB?
Yes, Springg JPA allows it, as well as to many other databases. You make compromises by using the JPA API for other types of datastores, but it makes it easy to investigate them
What is embedded MongoDB in Spring boot?
MongoDB has rapidly gained popularity in the enterprise and the Spring community. While developing and testing Spring Boot applications with MongoDB as the data store, it is common to use the lightweight Embedded MongoDB rather than running a full-fledged server.
In this article, we have seen the various examples of Spring Data MongoDB using MongoTemplate and MongoRepository .
0 Comments
Post a Comment