Skip to content
Divya D edited this page Apr 7, 2020 · 4 revisions

Welcome to the SpringBoot-Mongodb-project wiki!

SPRINGBOOT-MONGODB-PROJECT

A Restful webservice using SpringBoot and mongodb.

Getting Started

SPRING BOOT

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss.
Most Spring Boot applications need minimal Spring configuration.

Annotations

@Autowired: It is only applied to the bean property setter methods, constructors, non-setter methods and properties.
@SpringBootApplication:it notifies project as spring boot project
@RestController: it is a convenience annotation for creating Restful controllers.
@RequestMapping: it is one of the most common annotation used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers. In this post, you'll see how versatile the @RequestMapping annotation is when used to map Spring MVC controller methods.
@Controller: it annotation based approach where you don’t need to extend any base class to express request mappings, request input parameters, exception handling, and more. @Controller is similar annotation which mark a class as request handler.
@GetMapping: it is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET). @GetMapping annotated methods handle the HTTP GET requests matched with given URI expression
@PostMapping:it is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST). @PostMapping annotated methods handle the HTTP POST requests matched with given URI expression.
@PutMapping : it is an annotation for mapping HTTP PUT requests onto specific handler methods. @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping: it is an annotation for mapping HTTP DELETE requests onto specific handler methods.@DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).
@Document: it identifies a domain object to be persistented to database(mongoDB)
@Repository: it is a Spring annotation that indicates that the annotated class is a repository. A repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.
@Service: it is an operation offered as an interface that stands alone in the model with no encapsulated state.

Prerequisites

mongodb and intellij or eclispse should be installed in system.
link to download mongodb -> https://www.mongodb.com/download-center/community
link to download intellij -> https://www.jetbrains.com/idea/download/#section=windows
link to download eclipse -> https://www.eclipse.org/downloads

STEPS

step 1: The above mentioned prerequisites should be present. step 2: spring plugin should be installed in your selected editor
step 3: create a spring started booter project. GroupId, ArtifcatId, project name, project description should be filled while creating the project.
step 4: select dependencies, for this project selecet web and mongodb dependency and click next.The project is created with nessceary jar files and libraries.
step 5: In pom.xml you can verify the dependencies you included.
step 6: To link mongodb to the project write the following code in application.properties which is under resources folder.
spring.data.mongodb.uri=mongodb://localhost:27017/test
Here test is the Database name creadted in mongodb.
step 7: create a new class Student under com.example.demo.model package and put the student.java file present in the repository.
 
package com.example.demo.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Student")
public class Student {
    @Id
    String id;
    String firstName;
    String lastName;
    int age;
    int sem;
    String sec;
    String usn;
    public Student(String firstName,String lastName,int age,int sem,String sec,String usn)
    {
        this.firstName=firstName;
        this.lastName=lastName;
        this.age=age;
        this.sem=sem;
        this.sec=sec;
        this.usn=usn;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getSem() {
        return sem;
    }
    public void setSem(int sem) {
        this.sem = sem;
    }
    public String getSec() {
        return sec;
    }
    public void setSec(String sec) {
        this.sec = sec;
    }
    public String getUsn() {
        return usn;
    }
    public void setUsn(String usn) {
        this.usn = usn;
    }
    public String toString() {
        return "Person First Name:"+firstName+" Last Name:"+lastName+" age:"+age+"sem"+sem+"sec"+sec+"usn"+usn;
    }
}
step 8: create a new interface Repository under com.example.demo.Repository package and put the studentrepository.java file from the repository.

package com.example.demo.Repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Student;
@Repository
public interface StudentRepository extends MongoRepository{
     Student findByFirstName(String firstName);
     Student findByUsn(String usn);
}
step 9: create new class studentservice under com.example.demo.service package and put the code from studentservice.java file from the repository.

package com.example.demo.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Student;
import com.example.demo.Repository.StudentRepository;
@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    //Create operation
    public Student create(String firstName,String lastName, int age ,int sem, String sec,String usn) {
        return studentRepository.save(new Student(firstName, lastName, age,sem,sec,usn));
    }
    //Retrieve operation
    public List getAll(){
        return studentRepository.findAll();
    }
    public Student getByFirstName(String firstName) {
        return studentRepository.findByFirstName(firstName);
    }
    public Student getByUsn(String usn) {
        return studentRepository.findByUsn(usn);
    }
    //Update operation
    public Student update(String firstName, String lastName, int age,int sem, String sec, String usn) {
        Student p = studentRepository.findByFirstName(firstName);
        p.setLastName(lastName);
        p.setAge(age);
        p.setUsn(usn);
        p.setSem(sem);
        p.setSec(sec);
        return studentRepository.save(p);
    }
    public Student updaterecord(Student s, String usn) {
        Student p = studentRepository.findByUsn(usn);
        p.setFirstName(s.getFirstName());
        p.setLastName(s.getLastName());
        p.setAge(s.getAge());
        p.setSec(s.getSec());
        p.setSem(s.getSem());
        studentRepository.save(p);
        return p;
    }
    //Delete operation
    public void deleteAll() {
        studentRepository.deleteAll();
    }
    public void delete(String firstName) {
        Student p = studentRepository.findByFirstName(firstName);
        studentRepository.delete(p);
    }
    public void deletebyusn(String usn) {
        Student s =studentRepository.findByUsn(usn);
        studentRepository.delete(s);
    }
    public  void createrecord(Student person) {
        studentRepository.save(person);
    }
}
step 10: create a new class studentcontroller under com.example.demo.controller package and put the code from the studentcontroller.java file from repository.

package com.example.demo.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.demo.model.Student;
import com.example.demo.Service.StudentService;
@RestController@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @RequestMapping("/create")
    public String create(@RequestParam String firstName, @RequestParam String lastName, @RequestParam int age,@RequestParam int sem, @RequestParam String sec,@RequestParam String usn) {
        Student p = studentService.create(firstName, lastName, age,sem,sec,usn);
        return p.toString();
    }
    @PostMapping(value = "/")
    public ResponseEntity> saveOrUpdateStudent(@RequestBody Student person) {
        studentService.createrecord(person);
        return new ResponseEntity("Student added successfully", HttpStatus.OK);
    }
    @GetMapping(value="/firstname/{firstName}")
    public Student getstudentbyname(@PathVariable ("firstName") String firstName) {
        return studentService.getByFirstName(firstName);
    }
    @GetMapping(value="/usn/{usn}")
    public Student getstudentbyusn(@PathVariable ("usn") String usn) {
        return studentService.getByUsn(usn);
    }
    @GetMapping(value="/")
    public List getAll(){
        return studentService.getAll();
    }
    @RequestMapping("/update")
    public String update(@RequestParam String firstName, @RequestParam String lastName, @RequestParam int age, @RequestParam int sem, @RequestParam String sec,@RequestParam String usn) {
        Student p = studentService.update(firstName, lastName, age,sem,sec,usn);
        return p.toString();
    }
    @PutMapping(value="/{usn}")
    public Student updaterecord(@RequestBody Student s, @PathVariable ("usn") String usn) {
        Student p = studentService.updaterecord(s,usn);
        return p;
    }
    @RequestMapping("/delete")
    public String delete(@RequestParam String firstName) {
        studentService.delete(firstName);
        return "Deleted "+firstName;
    }
    @DeleteMapping(value="/firstname/{firstName}")
    public String deleterecord(@PathVariable("firstName") String firstName){
        studentService.delete(firstName);
        return "deleted"+firstName;
    }
    @DeleteMapping(value="/")
    public String deleteallrecord() {
        studentService.deleteAll();
        return "Deleted all the records from students";
    }
    @DeleteMapping(value="/usn/{usn}")
    public String deletebyusn(@PathVariable("usn") String usn) {
        studentService.deletebyusn(usn);
        return "deleted"+usn;
    }
    @RequestMapping ("/deleteAll")
    public String deleteAll() {
        studentService.deleteAll();
        return "Deleted all records";
    }
}
step 11: select studentapplication.java file and run it as it contains the main method.


Running Tests

1. In Web Browser

url -> http://localhost:8080/student/
For Post -> http://localhost:8080/student/create?firstName=nithya&lastName=VC&age=21&sem=6&sec=A&usn=1js17is041
For Update ->http://localhost:8080/student/update?firstName=divya&lastName=A&age=100&sem=8&sec=Z&usn=1js17is010
For delete -> http://localhost:8080/student/delete?firstName=divya
For get -> http://localhost:8080/student/
For getting by firstname -> http://localhost:8080/student/firstname/nith

2. In Postman

url -> http://localhost:8080/student/
For Post : url -> http://localhost:8080/student/"
Body ->
{
	"firstName":"randy",
	"lastName":"D",
	"age":9,
	"sem":1,
	"sec":"A",
	"usn":"1js17is001"
	}
For Put : url -> http://localhost:8080/student/1js17is001
Body ->

        {
	"firstName":"randy",
	"lastName":"r",
	"age":7,
	"sem":2,
	"sec":"A"
        }
For Delete(deleting by usn) : url -> http://localhost:8080/student/usn/1js17is001
For Delete(deleting by firstname) : url -> http://localhost:8080/student/firstname/nith
For Delete(deleting all record) : url -> http://localhost:8080/student/
For Get (getting by firstname) : url -> http://localhost:8080/student/firstname/nithya
For Get (getting by usn) : url -> http://localhost:8080/student/usn/1js17is041
For Get (getting all records) : url -> http://localhost:8080/student/