CRUD Tutorial using JAVA Spring boot microservices with Angular code examples

 Here's an example of creating a simple CRUD (Create, Read, Update, Delete) application using Java Spring Boot for the backend (Microservices) and Angular for the frontend.

1. Backend (Spring Boot - Microservice)

1.1 Set Up the Spring Boot Project

  • You can generate a Spring Boot project using Spring Initializr.
    • Dependencies: Spring Web, Spring Data JPA, H2 Database (for simplicity), Spring Boot DevTools.

1.2 Create the Model

Employee.java (The Entity representing an employee)

package com.example.demo.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Employee { @Id private Long id; private String name; private String position; // Constructors, Getters, and Setters public Employee() { } public Employee(Long id, String name, String position) { this.id = id; this.name = name; this.position = position; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } }

1.3 Create Repository Interface

EmployeeRepository.java (Using JPA)

package com.example.demo.repository; import com.example.demo.model.Employee; import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeeRepository extends JpaRepository<Employee, Long> { }

1.4 Create Service Class

EmployeeService.java

package com.example.demo.service; import com.example.demo.model.Employee; import com.example.demo.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class EmployeeService { @Autowired private EmployeeRepository employeeRepository; public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } public Optional<Employee> getEmployeeById(Long id) { return employeeRepository.findById(id); } public Employee saveEmployee(Employee employee) { return employeeRepository.save(employee); } public void deleteEmployee(Long id) { employeeRepository.deleteById(id); } }

1.5 Create Controller Class

EmployeeController.java

package com.example.demo.controller; import com.example.demo.model.Employee; import com.example.demo.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/api/employees") public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping public List<Employee> getAllEmployees() { return employeeService.getAllEmployees(); } @GetMapping("/{id}") public Optional<Employee> getEmployeeById(@PathVariable Long id) { return employeeService.getEmployeeById(id); } @PostMapping public Employee createEmployee(@RequestBody Employee employee) { return employeeService.saveEmployee(employee); } @PutMapping("/{id}") public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee employee) { employee.setId(id); return employeeService.saveEmployee(employee); } @DeleteMapping("/{id}") public void deleteEmployee(@PathVariable Long id) { employeeService.deleteEmployee(id); } }

1.6 Application Configuration

application.properties (For the H2 Database)

spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.h2.console.enabled=true

=================================================>

2. Frontend (Angular)

2.1 Create a New Angular Application

Generate a new Angular app using the following command:

ng new employee-crud-app cd employee-crud-app ng add @angular/material

Install HTTP client module if not already installed:

ng generate module app-routing --flat --module=app

2.2 Create a Service for CRUD Operations

employee.service.ts

import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; interface Employee { id: number; name: string; position: string; } @Injectable({ providedIn: 'root' }) export class EmployeeService { private apiUrl = 'http://localhost:8080/api/employees'; // URL to Spring Boot backend constructor(private http: HttpClient) { } getEmployees(): Observable<Employee[]> { return this.http.get<Employee[]>(this.apiUrl); } getEmployeeById(id: number): Observable<Employee> { return this.http.get<Employee>(`${this.apiUrl}/${id}`); } createEmployee(employee: Employee): Observable<Employee> { return this.http.post<Employee>(this.apiUrl, employee); } updateEmployee(id: number, employee: Employee): Observable<Employee> { return this.http.put<Employee>(`${this.apiUrl}/${id}`, employee); } deleteEmployee(id: number): Observable<void> { return this.http.delete<void>(`${this.apiUrl}/${id}`); } }

2.3 Create Component to Display and Handle Employees

employee.component.ts

import { Component, OnInit } from '@angular/core'; import { EmployeeService } from './employee.service'; @Component({ selector: 'app-employee', templateUrl: './employee.component.html', styleUrls: ['./employee.component.css'] }) export class EmployeeComponent implements OnInit { employees = []; employeeForm = { id: null, name: '', position: '' }; constructor(private employeeService: EmployeeService) { } ngOnInit(): void { this.getEmployees(); } getEmployees(): void { this.employeeService.getEmployees().subscribe(data => { this.employees = data; }); } createEmployee(): void { if (!this.employeeForm.id) { this.employeeService.createEmployee(this.employeeForm).subscribe(() => { this.getEmployees(); }); } else { this.employeeService.updateEmployee(this.employeeForm.id, this.employeeForm).subscribe(() => { this.getEmployees(); }); } } editEmployee(employee): void { this.employeeForm = { ...employee }; } deleteEmployee(id: number): void { this.employeeService.deleteEmployee(id).subscribe(() => { this.getEmployees(); }); } }

employee.component.html

<div> <h2>Employee List</h2> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Position</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let employee of employees"> <td>{{employee.id}}</td> <td>{{employee.name}}</td> <td>{{employee.position}}</td> <td> <button (click)="editEmployee(employee)">Edit</button> <button (click)="deleteEmployee(employee.id)">Delete</button> </td> </tr> </tbody> </table> <h3>{{ employeeForm.id ? 'Edit Employee' : 'Create Employee' }}</h3> <form (ngSubmit)="createEmployee()"> <input [(ngModel)]="employeeForm.name" name="name" placeholder="Name" required> <input [(ngModel)]="employeeForm.position" name="position" placeholder="Position" required> <button type="submit">{{ employeeForm.id ? 'Update' : 'Create' }}</button> </form> </div>

2.4 Add HttpClientModule to the App

Make sure to import the HttpClientModule in your app.module.ts file:

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { EmployeeComponent } from './employee/employee.component'; @NgModule({ declarations: [ AppComponent, EmployeeComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

3. Run the Application

3.1 Start the Backend

Run the Spring Boot application:

mvn spring-boot:run

3.2 Start the Frontend

Run the Angular application:

ng serve

Now, the Spring Boot backend will be running on http://localhost:8080, and the Angular frontend will be running on http://localhost:4200. You can create, read, update, and delete employee data via the frontend.


This is a simple example of a CRUD application using Java Spring Boot for the backend (Microservice) and Angular for the frontend. You can further enhance this by using more complex databases, adding validation, authentication, and other features based on your needs.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics