In this tutorial, we are going to show how to work with Spring Boot MongoDB with Spring Data.
Spring Boot MongoDB :
Technologies :
- Spring Boot 2.0.0.RELEASE
- Spring Boot Started Data Mongo 3.6.3
- Maven
- Java 8
Preparing MongoDB :
Install or setup MongoDB if you do not have and execute the below commands in MongoDB shell to create MongoDB document and inserting data.
> use otp
> db.item.insert({
itemId:1,
serialNumber:82,
category:"Books",
name:"MongoDB in Action"
})
> db.item.insert({
itemId:2,
serialNumber:20,
category:"Mobiles",
name:"iPhone6"
})
> db.item.insert({
itemId:3,
serialNumber:84,
category:"Books",
name:"Spring in Action"
})
> db.item.insert({
itemId:4,
serialNumber:24,
category:"Mobiles",
name:"Samsung Galaxy"
})
Created item document and inserted four items in it.
Spring Boot MongoDB Example :
Project Structure :
pom.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.onlinetutorialspoint</groupId>
<artifactId>SpringBoot_MongoDB_Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot_MongoDB_Example</name>
<description>Spring Boot MongoDB Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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>
<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>
application properties :
#mongodb properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=otp
Creating Model, which represents the MongoDB document.
Item.java
package com.onlinetutorialspoint.docs;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "item")
public class Item {
@Id
private String id;
private long itemId;
private String serialNumber;
private String category;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getItemId() {
return itemId;
}
public void setItemId(long itemId) {
this.itemId = itemId;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Creating a Spring Data + MongoDB repository.
Item Repository :
package com.onlinetutorialspoint.repository;
import com.onlinetutorialspoint.docs.Item;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface ItemRepository extends MongoRepository<Item,Long> {
List<Item> findByCategory(String category);
Item findByItemId(long itemId);
}
Creating Service class: Responsible to do all CRUD operations.
ItemService.java
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.docs.Item;
import com.onlinetutorialspoint.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ItemService {
@Autowired
ItemRepository itemRepo;
public List<Item> getAllItems(){
return itemRepo.findAll();
}
/*Getting a specific item by category from collection*/
public List<Item> getItemByCategory(String category){
List<Item> item = itemRepo.findByCategory(category);
return item;
}
/*Getting a specific item by item id from collection*/
public Item getItemByItemId(long itemId){
Item item = itemRepo.findByItemId(itemId);
return item;
}
/*Adding/inserting an item into collection*/
public Item addItem(long id,String serialNumber, String name,String category) {
Item item = new Item();
item.setCategory(category);
item.setItemId(id);
item.setName(name);
item.setSerialNumber(serialNumber);
return itemRepo.save(item);
}
/*delete an item from collection*/
public int deleteItem(long itemId){
Item item = itemRepo.findByItemId(itemId);
if(item != null){
itemRepo.delete(item);
return 1;
}
return -1;
}
}
Create a Spring Boot Rest Controller :
ItemController.java
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.docs.Item;
import com.onlinetutorialspoint.service.ItemService;
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 ItemController {
@Autowired
ItemService itemService;
@RequestMapping("/getAllItems")
@ResponseBody
public List<Item> getItems(){
return itemService.getAllItems();
}
@RequestMapping("/getItem")
@ResponseBody
public List<Item> getItem(@RequestParam("category") String category){
return itemService.getItemByCategory(category);
}
@RequestMapping("/getItemById")
@ResponseBody
public Item getItemById(@RequestParam("item") long item){
return itemService.getItemByItemId(item);
}
@RequestMapping("/addItem")
@ResponseBody
public String addItem(@RequestParam("itemId") long itemId,@RequestParam("serialNumber") String serialNumber,
@RequestParam("name") String name,
@RequestParam("category") String category){
if(itemService.addItem(itemId,serialNumber,name,category) != null){
return "Item Added Successfully";
}else{
return "Something went wrong !";
}
}
@RequestMapping("/deteteItem")
@ResponseBody
public String deteteItem(@RequestParam("itemId") int itemId){
if(itemService.deleteItem(itemId) == 1){
return "Item Deleted Successfully";
}else{
return "Something went wrong !";
}
}
}
Application.java
package com.onlinetutorialspoint;
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);
}
}
Run :
mvn clean install
mvn spring-boot:run
[INFO] --- spring-boot-maven-plugin:2.0.0.RELEASE:run (default-cli) @ SpringBoot_MongoDB_Example ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RELEASE)
2018-03-09 09:00:09.575 INFO 884 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 884 (E:\work\SpringBoot_MongoDB_Ex
ample\target\classes started by Lenovo in E:\work\SpringBoot_MongoDB_Example)
2018-03-09 09:00:09.601 INFO 884 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default
2018-03-09 09:00:10.033 INFO 884 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebS
erverApplicationContext@3d574a8d: startup date [Fri Mar 09 09:00:10 IST 2018]; root of context hierarchy
2018-03-09 09:00:13.358 INFO 884 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-03-09 09:00:13.465 INFO 884 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-03-09 09:00:13.466 INFO 884 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
.........
.........
Output :
Getting all Items :
http://localhost:8080/getAllItems
Get Item By a specific item Id :
http://localhost:8080/getItemById?item=2
Get Item By Category:
http://localhost:8080/getItem?category=Books
Insert item :
http://localhost:8080/addItem?itemId=5&serialNumber=28&name=Sony&category=Television
Delete Item :
http://localhost:8080/deteteItem?itemId=3
After Insert and Delete an item :
Reference :
Happy Learning 🙂