model code for spring boot crud with mongodb

Viewed 50

model code for spring boot crud with MongoDB

  • application properties samples
  • model classes samples
  • repositories samples
  • exception handling samples
2 Answers

application.properties

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=testtwo

model samples

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


@Document(collection = "Student1")
public class Students {
    
    @Id
    private String id;
    private String firstName;
    private String lastName;
    private String gender;
    
    
}

repositories

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.models.Students;

@Repository
public interface StudentRepostitary extends MongoRepository<Students,String>{
    
}

exeptions

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class StudentExeptions extends RuntimeException{
    
    public StudentExeptions(String message){
        super(message);
    }
}

controllers

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.exeptions.StudentExeptions;
import com.example.demo.models.Students;
import com.example.demo.repositarys.StudentRepostitary;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/students")
public class StudentController {
    @Autowired
    public StudentRepostitary studentRepostitary;

    @GetMapping("/")
    public List <Students> getAllStudents (){
        return studentRepostitary.findAll();
    }

    @GetMapping("/{id}")
    public Optional<Students> getStudent (@PathVariable String id){
        return studentRepostitary.findById(id);
    }

    @PostMapping("/")
    public Students addstudent (@RequestBody Students students){
        return studentRepostitary.save(students);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String,Boolean>> deleteStudent (@PathVariable String id){
        Students students = studentRepostitary.findById(id).orElseThrow(()-> new StudentExeptions("srudent Not Foound"));
        studentRepostitary.delete(students);
        Map<String,Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return ResponseEntity.ok(response);
    }

    @PutMapping("/{id}")
    public ResponseEntity <Students> updateStudents (@PathVariable String id, @RequestBody Students students){
        Students exsitingStudnt = studentRepostitary.findById(id).orElseThrow(()-> new StudentExeptions("not found"));
        exsitingStudnt.setFirstName(students.getFirstName());
        exsitingStudnt.setLastName(students.getLastName());
        exsitingStudnt.setGender(students.getGender());

        return ResponseEntity.ok(studentRepostitary.save(exsitingStudnt));

    }
}

dependencies

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.af.final</groupId>
    <artifactId>sringBack</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sringBack</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Related