Spring Boot MongoDB + Spring Data Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to show how to work with Spring Boot MongoDB with Spring Data.
Spring Boot 2.0.0.RELEASE
Spring Boot Started Data Mongo 3.6.3
Maven
Java 8
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.
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);
  }
}

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 :
 
Spring Boot with Spring Data Reference
MongoDB Official Tutorial
Happy Learning 🙂


SpringBoot MongoDB + Spring Data Example

File size: 93 KB
Downloads: 1023


Spring Boot MockMvc JUnit Test Example
Spring Boot In Memory Basic Authentication Security
Spring Boot Hazelcast Cache Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot Redis Cache Example – Redis Server
Spring boot exception handling rest service (CRUD) operations
Spring Boot Soap WebServices Example
Spring Boot Redis Data Example CRUD Operations
Spring Boot Multiple Data Sources Example
How to setup or install MongoDB on Windows 10
Spring Boot DataRest Example RepositoryRestResource
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
How to set Spring Boot Tomcat session timeout
Spring Boot H2 Database + JDBC Template Example

Spring Boot MockMvc JUnit Test Example
Spring Boot In Memory Basic Authentication Security
Spring Boot Hazelcast Cache Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot Redis Cache Example – Redis Server
Spring boot exception handling rest service (CRUD) operations
Spring Boot Soap WebServices Example
Spring Boot Redis Data Example CRUD Operations
Spring Boot Multiple Data Sources Example
How to setup or install MongoDB on Windows 10
Spring Boot DataRest Example RepositoryRestResource
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
How to set Spring Boot Tomcat session timeout
Spring Boot H2 Database + JDBC Template Example






SAtria
October 4, 2019 at 12:48 pm - Reply 

How to setup two datasource (mongodb different connection) in spring boot crud










SAtria
October 4, 2019 at 12:48 pm - Reply 

How to setup two datasource (mongodb different connection) in spring boot crud




How to setup two datasource (mongodb different connection) in spring boot crud
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment