Home Angular Spring boot with Angular Full Stack Application

Spring boot with Angular Full Stack Application

22 min read
0
0
6,499

Spring Boot is a powerful java framework which allow the user to quickly build the application. This tutorial will teach you how to do the full stack development application using Spring boot with Angular that are CREATE, RETIEVE, UPDATE and DELETE and SEARCH using mysql Database.Spring Boot is the backend and Angular is a  frontend to perform CRUD Application Step by step.

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.

Lets Started Project

Spring Boot – Back End Application

Angular – Front End Application

Learns Start Spring Boot.

First Step visit to Spring Initializer to configure the project using the following dependencies.

 

 

Create the Package Customer Controller

Inside the Package create the class CustomerController.java

CustomerController.java

package com.Project.SpringAngular.CustomerController;
import com.Project.SpringAngular.DTO.CustomerDTO;
import com.Project.SpringAngular.DTO.CustomerSaveDTO;
import com.Project.SpringAngular.DTO.CustomerUpdateDTO;
import com.Project.SpringAngular.Service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("api/v1/customer")
public class CustomerController
{
    @Autowired
    private CustomerService customerService;

    @PostMapping(path = "/save")

    public String saveCustomer(@RequestBody CustomerSaveDTO customerSaveDTO)
    {
        String id = customerService.addCustomer(customerSaveDTO);
        return id;
    }

    @GetMapping(path = "/getAllCustomer")
    public List<CustomerDTO> getAllCustomer()
    {
       List<CustomerDTO>allCustomers = customerService.getAllCustomer();
       return allCustomers;
    }

    @PutMapping(path = "/update")

    public String updateCustomer(@RequestBody CustomerUpdateDTO customerUpdateDTO)
    {
        String id = customerService.updateCustomers(customerUpdateDTO);
        return id;
    }

    @DeleteMapping(path = "/deletecustomer/{id}")
    public String deleteCustomer(@PathVariable(value = "id") int id)
    {
        boolean deletecustomer = customerService.deleteCustomer(id);
        return "deleted";
    }

}

Create the Package entity

Inside the Package create the class Customer

package com.Project.SpringAngular.entity;

import javax.persistence.*;
@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "customer_id", length = 50)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int customerid;

    @Column(name = "customer_name", length = 50)
    private String customername;

    @Column(name = "customer_address", length = 60)
    private String customeraddress;

    @Column(name = "mobile", length = 12)
    private int mobile;

    public Customer(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public Customer() {
    }

    public Customer(String customername, String customeraddress, int mobile) {
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

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

    @Override
    public String toString() {
        return "Customer{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}

Create the Package DTO

Inside the Package create the class CustomerDTO and CustomerSaveDTO and
CustomerUpdateDTO

CustomerDTO .java

package com.Project.SpringAngular.DTO;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class CustomerDTO {


    private int customerid;
    private String customername;
    private String customeraddress;
    private int mobile;

    public CustomerDTO(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public CustomerDTO() {
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

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

    @Override
    public String toString() {
        return "CustomerDTO{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}

CustomerSaveDTO

package com.Project.SpringAngular.DTO;

public class CustomerSaveDTO {

    private String customername;
    private String customeraddress;
    private int mobile;

    public CustomerSaveDTO(String customername, String customeraddress, int mobile) {
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public CustomerSaveDTO() {
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

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

    @Override
    public String toString() {
        return "CustomerSaveDTO{" +
                "customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}

CustomerUpdateDTO

package com.Project.SpringAngular.DTO;

public class CustomerUpdateDTO {
    private int customerid;
    private String customername;
    private String customeraddress;
    private int mobile;

    public CustomerUpdateDTO(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public CustomerUpdateDTO() {
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

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

    @Override
    public String toString() {
        return "CustomerDTO{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}

Create the Package Customer Service

Inside the Package create the interface CustomerService.java and CustomerServiceIMPL

CustomerService.java

package com.Project.SpringAngular.Service;

import com.Project.SpringAngular.DTO.CustomerDTO;
import com.Project.SpringAngular.DTO.CustomerSaveDTO;
import com.Project.SpringAngular.DTO.CustomerUpdateDTO;

import java.util.List;

public interface CustomerService {
    String addCustomer(CustomerSaveDTO customerSaveDTO);

    List<CustomerDTO> getAllCustomer();

    String updateCustomers(CustomerUpdateDTO customerUpdateDTO);

    boolean deleteCustomer(int id);
}

CustomerServiceIMPL.java

package com.Project.SpringAngular.Service;

import com.Project.SpringAngular.CustomerRepo.CustomerRepo;
import com.Project.SpringAngular.DTO.CustomerDTO;
import com.Project.SpringAngular.DTO.CustomerSaveDTO;
import com.Project.SpringAngular.DTO.CustomerUpdateDTO;
import com.Project.SpringAngular.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerServiceIMPL implements CustomerService
{
    @Autowired
    private CustomerRepo customerRepo;

    @Override
    public String addCustomer(CustomerSaveDTO customerSaveDTO)
    {
        Customer customer = new Customer(

                customerSaveDTO.getCustomername(),
                customerSaveDTO.getCustomeraddress(),
                customerSaveDTO.getMobile()
        );
        customerRepo.save(customer);
        return customer.getCustomername();
    }

    @Override
    public List<CustomerDTO> getAllCustomer() {
       List<Customer> getCustomers = customerRepo.findAll();
       List<CustomerDTO> customerDTOList = new ArrayList<>();
       for(Customer a:getCustomers)
       {
           CustomerDTO customerDTO = new CustomerDTO(

                   a.getCustomerid(),
                   a.getCustomername(),
                   a.getCustomeraddress(),
                   a.getMobile()
           );
           customerDTOList.add(customerDTO);
       }

       return  customerDTOList;
    }

    @Override
    public String updateCustomers(CustomerUpdateDTO customerUpdateDTO)
    {
        if (customerRepo.existsById(customerUpdateDTO.getCustomerid())) {
            Customer customer = customerRepo.getById(customerUpdateDTO.getCustomerid());


            customer.setCustomername(customerUpdateDTO.getCustomername());
            customer.setCustomeraddress(customerUpdateDTO.getCustomeraddress());
            customer.setMobile(customerUpdateDTO.getMobile());
            customerRepo.save(customer);
        }
            else
            {
                System.out.println("Customer ID do not Exist");
            }

                return null;
        }

    @Override
    public boolean deleteCustomer(int id) {

        if(customerRepo.existsById(id))
        {
            customerRepo.deleteById(id);
        }
        else
        {
            System.out.println("customer id not found");
        }

        return true;
    }
}

 

Create the Package Customer Controller

Inside the Package create the interface CustomerRepo.java

CustomerRepo.java

package com.Project.SpringAngular.CustomerRepo;

import com.Project.SpringAngular.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;

@EnableJpaRepositories
@Repository
public interface CustomerRepo extends JpaRepository<Customer,Integer> {
}

Do the Database Configuration in application.properties 

spring.application.name=crudnew
server.port=8084

spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/gmsschool?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root

#jpa vendor adapter configuration
spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true

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

npm install -g @angular/cli

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

After complete the installation then run the project using 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 Crud

FormModule
HttpClientModule

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomerComponent } from './customer/customer.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule

  
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

add these module into the app.module.ts file  then only we will manage the forms and Http requests

customer.compoent.html

<div class="container mt-4" >
 
<div class="card">
        <h1>Customer Registation</h1>
 
<form>
    <div class="form-group">
      <label>Name</label>
      <input type="text" [(ngModel)]="customername" [ngModelOptions]="{standalone: true}"  class="form-control" id="name" placeholder="Enter Name">
 
    </div>
 
    <div class="form-group">
        <label>address</label>
        <input type="text" [(ngModel)]="customeraddress" [ngModelOptions]="{standalone: true}"  class="form-control" id="address" placeholder="Enter address">
  
      </div>
 
      <div class="form-group">
        <label>Mobile</label>
        <input type="text" [(ngModel)]="mobile" [ngModelOptions]="{standalone: true}" class="form-control" id="mobile" placeholder="Enter Mobile">
  
      </div>
    
    <button type="submit" class="btn btn-primary mt-4" (click)="save()" >Submit</button>
  </form>
</div>
<div>
 
 
    <div class="container mt-4" >
 
        <h1>Customer Table</h1>
 
 
 
 
    <table class="table">
        <thead>
         <h1 *ngIf="!isResultLoaded">Loading.................</h1>
        
        <tr>
            <th scope="col">ID</th>
            <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 CustomerItem of CustomerArray">
 
            <th scope="row">{{CustomerItem.customerid  }}</th>
            <td>{{CustomerItem.customername  | uppercase}}</td>
            <td>{{CustomerItem.customeraddress }}</td>
            <td>{{CustomerItem.mobile }}</td>
 
            <td>
              <button type="button" class="btn btn-success" (click)="setUpdate(CustomerItem)">Edit</button>
              
              <button type="button" class="btn btn-danger" (click)="setDelete(CustomerItem)">Delete</button>
            
            </td>
          </tr>
          
        </tbody>
      </table>
 
 
    </div>

customer.component.ts

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

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

  CustomerArray : any[] = [];
  isResultLoaded = false;
  isUpdateFormActive = false;
 
  
  customername: string ="";
  customeraddress: string ="";
  mobile: Number =0;
 
  currentCustomerID = "";



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

  getAllCustomer()
  {
    
    this.http.get("http://localhost:8084/api/v1/customer/getAllCustomer")
  
    .subscribe((resultData: any)=>
    {
        this.isResultLoaded = true;
        console.log(resultData);
        this.CustomerArray = resultData;
    });
  }
 
  register()
  {
  
    let bodyData = {
      "customername" : this.customername,
      "customeraddress" : this.customeraddress,
      "mobile" : this.mobile
    };
 
    this.http.post("http://localhost:8084/api/v1/customer/save",bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Successfully");
        this.getAllCustomer();

        this.customername = '';
      this.customeraddress = '';
        this.mobile  = 0;
    });
  }
  setUpdate(data: any)
  {
   this.customername = data.customername;
   this.customeraddress = data.customeraddress;
   this.mobile = data.mobile;
   this.currentCustomerID = data.customerid;
  }
 
  UpdateRecords()
  {
    let bodyData = {
      "customerid" : this.currentCustomerID,
      "customername" : this.customername,
      "customeraddress" : this.customeraddress,
      "mobile" : this.mobile
    };
    
    this.http.put("http://localhost:8084/api/v1/customer/update",bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Updateddd")
        this.getAllCustomer();
        this.customername = '';
        this.customeraddress = '';
        this.mobile  = 0;
    });
  }
 
  save()
  {
    if(this.currentCustomerID == '')
    {
        this.register();
    }
      else
      {
       this.UpdateRecords();
      }      
 
  }
 
  setDelete(data: any)
  {
    
    
    this.http.delete("http://localhost:8084/api/v1/customer/deletecustomer"+ "/"+ data.customerid,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Deletedddd")
        this.getAllCustomer();

        this.customername = '';
      this.customeraddress = '';
        this.mobile  = 0;
  
    });
 
  }
 }

 

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

    Build a Full-Stack Node.js MongoDB CRUD App with JWT Authentication

    In this tutorial, we will teach the process of building a full-stack application using Nod…