# Simple Spring Boot with MongoDB

We are gonna make simple applications with Spring Boot and MongoDB

Go to the  [Spring initializr](https://start.spring.io/) chose `Java 8` and next necessary dependencies

```
Spring Boot 2.4.4
Spring Web
Spring Data MongoDB
``` 


When you download and import in your IDE it's time to make some code ;)

First, we are gonna make Person class in package `entity`


```
package com.spring.mongo.entity;


import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;


@Document(collection = "Person")
public class Person {

    @Id
    private String id;

    private String name;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

``` 

Next, in package `dao` we are going to make interface and DAO class



```
package com.spring.mongo.dao;

import com.spring.mongo.entity.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends MongoRepository<Person, String> {
}

``` 






```
package com.spring.mongo.dao;

import com.spring.mongo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Optional;

@Component
public class PersonDAO {

    @Autowired
    private final PersonRepository personRepository;

    public PersonDAO(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    public Person insertPerson(Person person){
        return personRepository.save(person);
    }

    public Collection<Person> getAllPerson(){
        return personRepository.findAll();
    }

    public Optional<Person> getPersonById(String id){
        return personRepository.findById(id);
    }

    public Person updatePersonById(String id, Person person){
        Optional<Person> findPerson = personRepository.findById(id);
        Person personToBeUpdate = findPerson.get();
        personToBeUpdate.setId(person.getId());
        personToBeUpdate.setName(person.getName());

        return personRepository.save(personToBeUpdate);
    }

    public void deletePersonById(String id){
        try {
            personRepository.deleteById(id);
        }catch (NoSuchElementException noSuchElementException){
            noSuchElementException.printStackTrace();
        }
    }
}


``` 

In package `service`


```
package com.spring.mongo.service;

import com.spring.mongo.dao.PersonDAO;
import com.spring.mongo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Optional;

@Service
public class PersonService {

    @Autowired
    private final PersonDAO personDAO;

    public PersonService(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }

    public Person insertPerson(Person person){
        return personDAO.insertPerson(person);
    }

    public Collection<Person> getAllPerson(){
        return personDAO.getAllPerson();
    }

    public Optional<Person> getPersonById(String id){
        return personDAO.getPersonById(id);
    }

    public Person updatePersonById(String id, Person person){
        return personDAO.updatePersonById(id, person);
    }

    public void deletePerson(String id){
        personDAO.deletePersonById(id);
    }
}

``` 
And last `controller`


```
package com.spring.mongo.controller;

import com.spring.mongo.entity.Person;
import com.spring.mongo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Optional;

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private final PersonService personService;

    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @PostMapping
    public Person insertPerson(@RequestBody Person person){
        return personService.insertPerson(person);
    }

    @GetMapping
    public Collection<Person> getAllPerson(){
        return personService.getAllPerson();
    }

    @GetMapping(path = "{id}")
    public Optional<Person> getPersonById(@PathVariable("id") String id){
        return personService.getPersonById(id);
    }

    @PutMapping(path = "/update/{id}")
    public Person updatePersonById(@PathVariable String id, @RequestBody Person person){
        return personService.updatePersonById(id, person);
    }

    @DeleteMapping(path = "/delete/{id}")
    public void deletePerson(@PathVariable String id){
         personService.deletePerson(id);
    }

}

``` 
In applications.properties add database name
`spring.data.mongodb.database=springbootwithmongo`

Now run mongo in docker. Go to the project folder and run next command 
`docker-compose up -d`. If you don't know how, please read my  [article](https://mire.hashnode.dev/docker-container-deployment-with-mongodb) 


We will post few persons

![03 post.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506122059/ITVFLfxvQY.png)

![04 post.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506131702/C0Mnj8kWD.png)

Now we are gonna see all persons that are saved

![05 get.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506225599/EFFZI3bk3.png)

Now, we are gonna update one person

![05 put.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506260227/-RIFzQRrT.png)



![07 get.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506278572/poelmVJ2-.png)

Delete one person

![08 delete.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506356320/8YpFMU5CI.png)


![09 get.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616506362097/Apznat9IW.png)

As you can see, it takes few clicks and few lines of code to make a simple application with Spring Boot and Mongo in Docker

Here is  [link](https://github.com/mirkomiredjuric/SpringBootWithMongoDB)  to github.

## Thank you for reading

# If you like what you read and want to see more, please support me with  [coffee or a beer](https://www.buymeacoffee.com/mire)  ;) 
