Spring Boot Integration With MongoDB as a Maven Project
Last Updated :
11 Oct, 2022
MongoDB is a NoSQL database and it is getting used in software industries a lot because there is no strict schema like RDBMS that needs to be observed. It is a document-based model and less hassle in the structure of the collection. In this article let us see how it gets used with SpringBoot as a Maven project.
Implementation
Project Structure:
As it is a maven project, let's start with adding dependencies via
pom.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>SpringBoot_MongoDB_SampleProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot_MongoDB_SampleProject</name>
<description>SpringBoot_MongoDB_SampleProject</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<!-- For MongoDB connectivity -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
File to mention the connectivity with MongoDB database
application.properties
#mongodb properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=geeksforgeeks # Change the database as per your choice here
Let's start with the bean (document) file first
Book.java
Java
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "book")
public class Book {
@Id
private String id;
private long bookId;
private String isbnNumber;
private String category;
private String bookName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public String getIsbnNumber() {
return isbnNumber;
}
public void setIsbnNumber(String isbnNumber) {
this.isbnNumber = isbnNumber;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
}
BookRepository.java
Java
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.gfg.docs.Book;
public interface BookRepository extends MongoRepository<Book,Long> {
// Need to add all the required methods here
List<Book> findByCategory(String category);
Book findByBookId(long bookId);
}
Let's add the service file now
BookService.java
Java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gfg.docs.Book;
import com.gfg.repository.BookRepository;
@Service
public class BookService {
@Autowired
BookRepository bookRepository;
public List<Book> getAllBooks(){
return bookRepository.findAll();
}
// Getting a specific book by category from collection
public List<Book> getBookByCategory(String category){
List<Book> book = bookRepository.findByCategory(category);
return book;
}
// Getting a specific book by book id from collection
public Book getBookByBookId(long bookId){
Book book = bookRepository.findByBookId(bookId);
return book;
}
// Adding/inserting a book into collection
public Book addBook(long id,String isbnNumber, String bookName,String category) {
Book book = new Book();
book.setCategory(category);
book.setBookId(id);
book.setBookName(bookName);
book.setIsbnNumber(isbnNumber);
return bookRepository.save(book);
}
// Delete a book from collection
public int deleteBook(long bookId){
Book book = bookRepository.findByBookId(bookId);
if(book != null){
bookRepository.delete(book);
return 1;
}
return -1;
}
}
Now let's go to the controller file
BookController.java
Java
import com.gfg.docs.Book;
import com.gfg.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class BookController {
@Autowired
BookService bookService;
@RequestMapping("/getAllBooks")
@ResponseBody
public List<Book> getBooks(){
return bookService.getAllBooks();
}
@RequestMapping("/getBook")
@ResponseBody
public List<Book> getBook(@RequestParam("category") String category){
return bookService.getBookByCategory(category);
}
@RequestMapping("/getBookById")
@ResponseBody
public Book getBookById(@RequestParam("bookId") long bookId){
return bookService.getBookByBookId(bookId);
}
@RequestMapping("/addBook")
@ResponseBody
public String addBook(@RequestParam("bookId") long bookId,@RequestParam("isbnNumber") String isbnNumber,
@RequestParam("bookName") String bookName,
@RequestParam("category") String category){
if(bookService.addBook(bookId,isbnNumber,bookName,category) != null){
return "Book got Added Successfully";
}else{
return "Something went wrong !";
}
}
@RequestMapping("/deleteBook")
@ResponseBody
public String deleteBook(@RequestParam("bookId") int bookId){
if(bookService.deleteBook(bookId) == 1){
return "Book got Deleted Successfully";
}else{
return "Something went wrong !";
}
}
}
Main file that contains the main method and can be used to run as a Java application
Application.java
Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Steps to clean the project
mvn clean install # As this is maven project
Run the project
mvn spring-boot:run
Output:
We can test the same in the below ways. First, let us add the book
URL: http://localhost:8080/addBook?bookId=1&isbnNumber=12345&bookName=JavaBasics&category=Programming
Now list out the books
URL: http://localhost:8080/getAllBooks
Let's add 2 more books
We can search books by means of category
URL: http://localhost:8080/getBook?category=Programming
Similarly, we can do it by bookId as well
Like this, we can do all business logic as per our needs. It is quite easier to integrate MongoDB with SpringBoot technologies.
Similar Reads
Spring Boot | How to publish JSON messages on Apache Kafka
Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, ref
4 min read
Spring Boot - Consume JSON Object From Kafka Topics
Apache Kafka is a publish-subscribe messaging system. A messaging system lets someone is sending messages between processes, applications, and servers. Broadly Speaking, Apache Kafka is software where topics (A topic might be a category) can be defined and further processed. Applications may connect
4 min read
Spring Boot Kafka Producer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot Kafka Consumer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Message Compression in Apache Kafka using Spring Boot
Generally, producers send text-based data, such as JSON data. It is essential to apply compression to the producer in this situation. Producer messages are transmitted uncompressed by default. There are two types of Kafka compression. 1. Producer-Level Kafka Compression When compression is enabled o
4 min read
Spring Boot - Create and Configure Topics in Apache Kafka
Topics are a special and essential component of Apache Kafka that are used to organize events or messages. In other words, Kafka Topics enable simple data transmission and reception across Kafka Servers by acting as Virtual Groups or Logs that store messages and events in a logical sequence. In this
2 min read
How to Test Spring Boot Project using ZeroCode?
Zerocode automated testing framework for a REST API project concept is getting seen via this tutorial by taking a sample spring boot maven project. Let us see the dependencies for Zerocode : <dependency> <groupId>org.jsmart</groupId> <artifactId>zerocode-tdd</artifactId
5 min read
Validation in Spring Boot
In this article, via a Gradle project, let us see how to validate a sample application and show the output in the browser. The application is prepared as of type Spring Boot and in this article let us see how to execute via the command line as well. Example Project Project Structure: Â As this is th
5 min read
Spring Boot â Validation using Hibernate Validator
Hibernate Validator provides a powerful and flexible way to validate data in Spring Boot applications. Validating user input is essential for building secure and reliable applications. Spring Boot makes this easy with Hibernate Validator, the reference implementation of JSR 380 (Bean Validation API)
6 min read
How to Connect MongoDB with Spring Boot?
In recent times MongoDB has been the most used database in the software industry. It's easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we conne
4 min read