Spring Boot 2 PDF
Spring Boot 2 PDF
Link: https://www.javaguides.net/2019/02/spring-boot-2-angular-7-crud-example-
tutorial.html?fbclid=IwAR3dtxbT_pKqVJL8g_XlBH55JxdkH2tfa66mWmKvx1Ls_TcU6J87bvHAi5M
In this tutorial, we will learn how to develop a CRUD (Create, Read, Update, Delete) Web
Application using Angular 7 as a front-end and Spring boot 2 restful API as a backend.
If you are looking for Angular 6 with spring boot 2 integration example then check
out Spring Boot + Angular 6 CRUD Example article.
You can download the source code of this tutorial from my GitHub repository at end of
this tutorial.
Server-side technologies
Angular 7.2
Bootstrap 4
npm- 6.4.1
JQuery
Tools
Maven - 3.2+
IDE - Eclipse or Spring Tool Suite (STS)
Visual Studio 2017
Angular CLI
Let's first we will build a CRUD RESTFul APIs for a Simple Employee Management
System using Spring Boot 2 JPA and MySQL. Later we will consume these Rest APIs using
Angular 7 client application. Following are five REST APIs (Controller handler methods) are
created for Employee resource.
There are many ways to create a Spring Boot application. The simplest way is to use Spring
Initializrat http://start.spring.io/, which is an online Spring Boot application generator.
Look at the above diagram, we have specified the following details:
Once, all the details are entered, click on Generate Project button will generate a spring boot project
and downloads it. Next, Unzip the downloaded zip file and import it into your favorite IDE.
2. Packaging Structure
<groupId>net.guides.springboot2</groupId>
<artifactId>springboot2-jpa-crud-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot2-jpa-crud-example</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-
8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
4. Configuring MySQL Database
spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5InnoDBDialect
Change the above configuration such as JDBC URL, username and password as per your
environment.
package net.guides.springboot2.springboot2jpacrudexample.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employees")
public class Employee {
public Employee() {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ",
lastName=" + lastName + ", emailId=" + emailId
+ "]";
}
package net.guides.springboot2.springboot2jpacrudexample.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,
Long>{
package net.guides.springboot2.springboot2jpacrudexample.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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
net.guides.springboot2.springboot2jpacrudexample.exception.ResourceNotFou
ndException;
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
import
net.guides.springboot2.springboot2jpacrudexample.repository.EmployeeRepos
itory;
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value =
"id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not
found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee)
{
return employeeRepository.save(employee);
}
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value =
"id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws
ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not
found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee =
employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value =
"id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not
found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
8. Running Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application.
Or you can start spring boot application via command line using mvn spring-boot:run command.
This completes the development of Spring boot CRUD Rest APIs. Now we will develop client
application using Angular 7.
Let's develop a step by step CRUD (Create, Read, Update, Delete) Web Application using
Angular 7 which consume above CRUD rest APIs.
Good to know Angular 7 release notes and new features at Version 7 of Angular — CLI
Prompts, Virtual Scroll, Drag and Drop and more.
I assume that you have installed Node.js. Now, we need to check the Node.js and NPM
versions. Open the terminal or Node command line then type this commands.
node -v
v8.12.0
npm -v
6.4.1
That's the Node.js and NPM version that we are using. Now, you can go to the main steps.
Package Version
------------------------------------------------------
@angular-devkit/architect 0.10.1
@angular-devkit/core 7.0.1
@angular-devkit/schematics 7.0.1
@schematics/angular 7.0.1
@schematics/update 0.10.1
rxjs 6.3.3
typescript 3.1.3
Next, create a new Angular 7 Web Application using this Angular CLI command.
The Angular CLI is a command-line interface tool that you use to initialize, develop,
scaffold, and maintain Angular applications.
If you are new to Angular CLI then check out official documentation
at https://cli.angular.io.
Let's use below command to generate an Angular 7 Client application. We name this
project as "angular7-springboot-client".
ng new angular7-springboot-client
Components, Services, and Modules
Let's list out what are components, service, and modules we are going to create in this
application. We will use Angular CLI to generate components, services because Angular
CLI follows best practices and saves much of time.
1. Components
create-employee
employee-list
employee-details
2. Services
3. Modules
FormsModule
HttpClientModule
AppRoutingModule.
In this next step, we will generate these components, classes, and services using Angular
CLI.
- ng g s employee
– ng g c create-employee
– ng g c employee-details
– ng g c employee-list
C:\angular7\angular7-springboot-client\src\app>ng g s employee
CREATE src/app/employee.service.spec.ts (343 bytes)
CREATE src/app/employee.service.ts (137 bytes)
C:\angular7\angular7-springboot-client\src\app>ng g c create-employee
CREATE src/app/create-employee/create-employee.component.html (34 bytes)
CREATE src/app/create-employee/create-employee.component.spec.ts (685
bytes)
CREATE src/app/create-employee/create-employee.component.ts (304 bytes)
CREATE src/app/create-employee/create-employee.component.css (0 bytes)
UPDATE src/app/app.module.ts (509 bytes)
C:\angular7\angular7-springboot-client\src\app>ng g c employee-details
CREATE src/app/employee-details/employee-details.component.html (35
bytes)
CREATE src/app/employee-details/employee-details.component.spec.ts (692
bytes)
CREATE src/app/employee-details/employee-details.component.ts (308 bytes)
CREATE src/app/employee-details/employee-details.component.css (0 bytes)
UPDATE src/app/app.module.ts (629 bytes)
C:\angular7\angular7-springboot-client\src\app>ng g c employee-list
CREATE src/app/employee-list/employee-list.component.html (32 bytes)
CREATE src/app/employee-list/employee-list.component.spec.ts (671 bytes)
CREATE src/app/employee-list/employee-list.component.ts (296 bytes)
CREATE src/app/employee-list/employee-list.component.css (0 bytes)
UPDATE src/app/app.module.ts (737 bytes)
We will use Bootstrap 4 for styling our application so let's integrate bootstrap 4 with
Angular 7.
Use NPM to download Bootstrap & JQuery. Bootstrap and jQuery will be installed into the
node_modules folder.
...
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
...
Let's discuss each of the above generate components and service files and we will
customize it as per our requirement.
package.json
This file Configures npm package dependencies that are available to all projects in the
workspace.
Note that angular version 7.2.0 in dependencies section in below file.
{
"name": "angular7-springboot-client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~7.2.0",
"@angular/common": "~7.2.0",
"@angular/compiler": "~7.2.0",
"@angular/core": "~7.2.0",
"@angular/forms": "~7.2.0",
"@angular/platform-browser": "~7.2.0",
"@angular/platform-browser-dynamic": "~7.2.0",
"@angular/router": "~7.2.0",
"bootstrap": "^4.2.1",
"core-js": "^2.5.4",
"jquery": "^3.3.1",
"rxjs": "~6.3.3",
"tslib": "^1.9.0",
"zone.js": "~0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.12.0",
"@angular/cli": "~7.2.1",
"@angular/compiler-cli": "~7.2.0",
"@angular/language-service": "~7.2.0",
"@types/node": "~8.9.4",
"@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3",
"codelyzer": "~4.5.0",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~3.1.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.2.2"
}
}
Create Employee class - employee.ts
Before defining the EmployeeListComponent, let’s define an Employee class for working
with employees. create a new file employee.ts inside src/app folder and add the
following code to it -
EmployeeService - employee-list.component.ts
The EmployeeService will be used to get the data from backend by calling spring boot
APIs. Update the employee.service.ts file inside src/app directory with the following
code to it -
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
EmployeeListComponent - employee-list.component.ts
Let's update the EmployeeListComponent component which will be used to display a list
of employee, create a new employee, and delete an employee.
@Component({
selector: "app-employee-list",
templateUrl: "./employee-list.component.html",
styleUrls: ["./employee-list.component.css"]
})
export class EmployeeListComponent implements OnInit {
employees: Observable<Employee[]>;
ngOnInit() {
this.reloadData();
}
reloadData() {
this.employees = this.employeeService.getEmployeesList();
}
deleteEmployee(id: number) {
this.employeeService.deleteEmployee(id)
.subscribe(
data => {
console.log(data);
this.reloadData();
},
error => console.log(error));
}
}
Create a template for EmployeeListComponent - employee-list.component.html
CreateEmployeeComponent - create-employee.component.ts
CreateEmployeeComponent is used to create and handle a new employee form data. Add
the following code to it -
@Component({
selector: 'app-create-employee',
templateUrl: './create-employee.component.html',
styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
ngOnInit() {
}
newEmployee(): void {
this.submitted = false;
this.employee = new Employee();
}
save() {
this.employeeService.createEmployee(this.employee)
.subscribe(data => console.log(data), error => console.log(error));
this.employee = new Employee();
}
onSubmit() {
this.submitted = true;
this.save();
}
}
<h3>Create Employee</h3>
<div [hidden]="submitted" style="width: 400px;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">First Name</label>
<input type="text" class="form-control" id="firstName"
required [(ngModel)]="employee.firstName" name="firstName">
</div>
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control" id="lastName"
required [(ngModel)]="employee.lastName" name="lastName">
</div>
<div class="form-group">
<label for="name">First Name</label>
<input type="text" class="form-control" id="emailId" required
[(ngModel)]="employee.emailId" name="emailId">
</div>
<div [hidden]="!submitted">
<h4>You submitted successfully!</h4>
</div>
EmployeeDetailsComponent- employee-details.component.ts
@Component({
selector: 'app-employee-details',
templateUrl: './employee-details.component.html',
styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {
ngOnInit() {
}
}
<div *ngIf="employee">
<div>
<label>Name: </label> {{employee.firstName}}
</div>
<div>
<label>Age: </label> {{employee.lastName}}
</div>
<div>
<label>Active: </label> {{employee.emailId}}
</div>
<div>
<label>Active: </label> {{employee.active}}
</div>
<span class="button is-small btn-primary" *ngIf='employee.active'
(click)='updateActive(false)'>Inactive</span>
<hr/>
</div>
AppRoutingModule - app-routing.module.ts
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
AppComponent - app/app.component.ts
Defines the logic for the app's root component, named AppComponent. The view
associated with this root component becomes the root of the view hierarchy as you add
components and services to your app.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 + Spring Boot 2 + Spring Data JPA + MySQL + CRUD
Tutorial';
}
app/app.component.html
<div class="container">
<h2>{{title}}</h2>
<hr>
</nav>
<router-outlet></router-outlet>
</div>
app/app.module.ts
Defines the root module, named AppModule, that tells Angular how to assemble the
application. Initially declares only the AppComponent. As you add more components to the
app, they must be declared here.
As we already started Spring boot application. Now let's run this Angular 7 application.
Let's run the above developed Angular App with a command: ng serve
Output
Delete Employee
Note that update employee functionality is not implemented so you can take as exercise
and try to implement yourself (Tip: Add an update button to the employee list page and
based on employee id you can implement update functionality. Note that Rest API is
already created for update employee functionality).