Home Angular Spring boot with Angular MongoDb Full Stack

Spring boot with Angular MongoDb Full Stack

13 min read
0
0
2,390

This  tutorial will teach you how to do the full stack development application using Spring boot with Angular and mongoDB you how to do basic database functions that are CREATE RETIEVE, UPDATE and DELETE  using mongoDB Database.

Crud function how to perform the RESTful Web Service let discuss with following annotations.

@PostMapping:  annotation which used to create new record.
@GetMapping:   annotation which used to reads a record.
@RequestMapping: annotation which used to search the record.
@PutMapping:   annotation which used to update the existing record.
@DeleteMapping:  annotation which used to delete the record.

First Create the Controller

StudentController

package com.example.SpringMongoProject.Controller;

import com.example.SpringMongoProject.Entity.Student;
import com.example.SpringMongoProject.Service.StudentServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("api/v1/student")
public class StudentController {

    @Autowired
    private StudentServices studentServices;

    @PostMapping(value = "/save")
    private String saveStudent(@RequestBody Student students) {

        studentServices.saveorUpdate(students);
        return students.get_id();
    }
    
    @GetMapping(value = "/getall")
    public Iterable<Student> getStudents() {
        return studentServices.listAll();
    }

    @PutMapping(value = "/edit/{id}")
    private Student update(@RequestBody Student student, @PathVariable(name = "id") String _id) {
        student.set_id(_id);
        studentServices.saveorUpdate(student);
        return student;
    }

    @DeleteMapping("/delete/{id}")
    private void deleteStudent(@PathVariable("id") String _id) {
        studentServices.deleteStudent(_id);
    }


    @RequestMapping("/search/{id}")
    private Student getStudents(@PathVariable(name = "id") String studentid) {
        return studentServices.getStudentByID(studentid);
    }

}

Create the Entity

Student

package com.example.SpringMongoProject.Entity;

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

@Document(collection ="students")
public class Student {

    @Id
    private String _id;
    private String studentname;
    private String studentaddress;
    private String mobile;


    public Student(String _id, String studentname, String studentaddress, String mobile) {
        this._id = _id;
        this.studentname = studentname;
        this.studentaddress = studentaddress;
        this.mobile = mobile;
    }


    public Student() {
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getStudentname() {
        return studentname;
    }

    public void setStudentname(String studentname) {
        this.studentname = studentname;
    }

    public String getStudentaddress() {
        return studentaddress;
    }

    public void setStudentaddress(String studentaddress) {
        this.studentaddress = studentaddress;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "Student{" +
                "_id='" + _id + '\'' +
                ", studentname='" + studentname + '\'' +
                ", studentaddress='" + studentaddress + '\'' +
                ", mobile='" + mobile + '\'' +
                '}';
    }
}

Create repository

StudentRepo

package com.example.SpringMongoProject.Repo;

import com.example.SpringMongoProject.Entity.Student;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepo extends MongoRepository<Student,String> {
}

Create Service

StudentServices

package com.example.SpringMongoProject.Service;

import com.example.SpringMongoProject.Entity.Student;
import com.example.SpringMongoProject.Repo.StudentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServices {

    @Autowired
    private StudentRepo repo;

    public void saveorUpdate(Student students) {

        repo.save(students);
    }

    public Iterable<Student> listAll() {

        return this.repo.findAll();
    }


    public void deleteStudent(String id) {

        repo.deleteById(id);
    }

    public Student getStudentByID(String studentid) {

        return repo.findById(studentid).get();
    }
}

Angular

Angular is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.

Installing Angular CLI

After that create the new Project of Angular running by the following command

Now you see the Angular Welcome Page.

After that open the Angular project into VS code editor.

now you can see the following file structure

Creating a new Component Student

ng g c student

student.component.html

<div class="container mt-4" >
    <h1>STUDENT Registation</h1>
    <div class="card">
           
<form>
   
    <div class="form-group">
      <label >Student Name</label>
      <input type="text"  [(ngModel)]="studentname" [ngModelOptions]="{standalone: true}"   class="form-control" id="studentname" name="studentname" placeholder="Enter Name">
    </div>
    
    <div class="form-group">
        <label >Address</label>
        <input type="text" [(ngModel)]="studentaddress" [ngModelOptions]="{standalone: true}" class="form-control" id="studentaddress" name="studentaddress" placeholder="Enter Address">
      </div>

      <div class="form-group">
        <label >Mobile</label>
        <input type="text" [(ngModel)]="mobile" [ngModelOptions]="{standalone: true}" class="form-control" id="mobile" name="text" placeholder="Enter Mobile">
      </div>

      <button type="submit" class="btn btn-primary mt-4" (click)="save()" >Submit</button>
  </form>
</div>
</div>


<div>
 
    <div class="container mt-4" >
 
        <h1>Student Table</h1>
    <table class="table">
        <thead>     
        <tr>

            <th scope="col">Name</th>
            <th scope="col">Address</th>
            <th scope="col">Mobile</th>
            <th scope="col">Option</th>
          </tr>
        </thead>
        <tbody>
            <tr *ngFor="let StudentItem of StudentArray">
           
            <td>{{StudentItem.studentname}}</td>
            <td>{{StudentItem.studentaddress }}</td>
            <td>{{StudentItem.mobile }}</td>
 
            <td>
                <button type="button" class="btn btn-success" (click)="setUpdate(StudentItem)">Edit</button>
                <button type="button" class="btn btn-danger" (click)="setDelete(StudentItem)">Delete</button>
            </td>
          </tr>
          
        </tbody>
      </table>
 
 
    </div>

student.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.scss']
})
export class StudentComponent {


  StudentArray : any[] = [];


  studentname: string ="";
  studentaddress: string ="";
  mobile: Number =0;
 
  currentStudentID = "";


  constructor(private http: HttpClient )
  {
    this.getAllStudent();
 
  }

  register()
  {
  
    let bodyData = {
      "studentname" : this.studentname,
      "studentaddress" : this.studentaddress,
      "mobile" : this.mobile
    };
 
    this.http.post("http://localhost:8081/api/v1/student/save",bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Successfully");
        this.getAllStudent();
 
        this.studentname = '';
        this.studentaddress = '';
        this.mobile  = 0;
    });
  }


  getAllStudent()
  {
    
    this.http.get("http://localhost:8081/api/v1/student/getall")
  
    .subscribe((resultData: any)=>
    {
    
        console.log(resultData);
        this.StudentArray = resultData;
    });
  }


  setUpdate(data: any)
  {
   this.studentname = data.studentname;
   this.studentaddress = data.studentaddress;
   this.mobile = data.mobile;
   this.currentStudentID = data._id;
   
  }


 
  UpdateRecords()
  {
    let bodyData = {
     
      "studentname" : this.studentname,
      "studentaddress" : this.studentaddress,
      "mobile" : this.mobile
    };
    
    this.http.put("http://localhost:8081/api/v1/student/edit"+ "/" + this.currentStudentID , bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Registered Updateddd")
        this.getAllStudent();
 
        this.studentname = '';
        this.studentaddress = '';
        this.mobile  = 0;
    });
  }
 
  save()
  {
    if(this.currentStudentID == '')
    {
        this.register();
    }
      else
      {
       this.UpdateRecords();
      }      
 
  }
 
  setDelete(data: any)
  {
    
    
    this.http.delete("http://localhost:8081/api/v1/student/delete"+ "/"+ data._id,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Student Deletedddd")
        this.getAllStudent();
 
        this.studentname = '';
        this.studentaddress = '';
        this.mobile  = 0;
  
    });
 
  }


}

app.module.ts  add the following modules.

FormsModule, HttpClientModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StudentComponent } from './student/student.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent,
    StudentComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

i have attached the video link below. which will do this tutorials step by step.

 

    Load More Related Articles
    Load More By admin
    Load More In Angular

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Check Also

    Inventory management system using React

    In today’s fast-paced business environment, an efficient inventory management system…