1. Create Spring boot application
Spring Boot provides a web tool called Spring Initializer to bootstrap an application quickly. Just go to https://start.spring.io/ and generate a new spring boot project.
Use the below details in the Spring boot creation:
Project Name: springboot-backend
Project Type: Maven
Choose dependencies: Spring Web, Lombok, Spring Data JPA, and MySQL Driver
Package name: net.javaguides.springboot
Packaging: Jar
Download Spring Boot project as a zip file, unzip it, and import it into IntelliJ IDEA.
Here is the pom.xml file for your reference:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>springboot-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-backend</name>
<description>Demo project for Spring Boot REST APIs</description>
<properties>
<java.version>11</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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. Create Project or Packaging Structure
3. Configure MySQL Database
spring.datasource.url=jdbc:mysql://localhost:3306/ems?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
4. Create JPA Entity
package net.javaguides.springboot.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email_id")
private String emailId;
}
5. Create Spring Data JPA Repository
package net.javaguides.springboot.repository;
import net.javaguides.springboot.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
// all crud database methods
}
6. Create ResourceNotFoundException Custom Exception
Go to an exception package, create a class named ResourceNotFoundException and add the following content to it:
package net.javaguides.springboot.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{
public ResourceNotFoundException(String message){
super(message);
}
}
7. Creating Spring Boot CRUD REST APIs
Go to controller package, create a class named EmployeeController and add the following content to it:
package net.javaguides.springboot.controller;
import net.javaguides.springboot.exception.ResourceNotFoundException;
import net.javaguides.springboot.model.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin("*")
@RestController
@RequestMapping("/api/v1/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping
public List<Employee> getAllEmployees(){
return employeeRepository.findAll();
}
// build create employee REST API
@PostMapping
public Employee createEmployee(@RequestBody Employee employee) {
return employeeRepository.save(employee);
}
// build get employee by id REST API
@GetMapping("{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable long id){
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id:" + id));
return ResponseEntity.ok(employee);
}
// build update employee REST API
@PutMapping("{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable long id,@RequestBody Employee employeeDetails) {
Employee updateEmployee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id: " + id));
updateEmployee.setFirstName(employeeDetails.getFirstName());
updateEmployee.setLastName(employeeDetails.getLastName());
updateEmployee.setEmailId(employeeDetails.getEmailId());
employeeRepository.save(updateEmployee);
return ResponseEntity.ok(updateEmployee);
}
// build delete employee REST API
@DeleteMapping("{id}")
public ResponseEntity<HttpStatus> deleteEmployee(@PathVariable long id){
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id: " + id));
employeeRepository.delete(employee);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
Get All Employees REST API: @GetMapping
public List<Employee> getAllEmployees(){
return employeeRepository.findAll();
}
Create Employee REST API:
// build create employee REST API
@PostMapping
public Employee createEmployee(@RequestBody Employee employee) {
return employeeRepository.save(employee);
}
Get Employee by Id REST API:
// build get employee by id REST API
@GetMapping("{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable long id){
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id:" + id));
return ResponseEntity.ok(employee);
}
Update Employee REST API:
// build update employee REST API
@PutMapping("{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable long id,@RequestBody Employee employeeDetails) {
Employee updateEmployee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id: " + id));
updateEmployee.setFirstName(employeeDetails.getFirstName());
updateEmployee.setLastName(employeeDetails.getLastName());
updateEmployee.setEmailId(employeeDetails.getEmailId());
employeeRepository.save(updateEmployee);
return ResponseEntity.ok(updateEmployee);
}
Delete Employee REST API:
// build delete employee REST API
@DeleteMapping("{id}")
public ResponseEntity<HttpStatus> deleteEmployee(@PathVariable long id){
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id: " + id));
employeeRepository.delete(employee);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
8. Running the Application
$ mvn spring-boot:run
9. Testing CRUD REST APIs using Postman
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
All kinds of apps are available here. It's An Amazing Site.
ReplyDeletereally a nice post!
JetBrains PhpStorm Crack
Appreciation is a wonderful thing...thanks for sharing kepp it up.
ReplyDeletePostman Crack
Such a Nice post. Thanks for Awesome tips Keep it up .
ReplyDeleteJetbrains IntelliJ IDEA Crack
windowsup.net
Super helpful for beginner like me
ReplyDeleteGreat job on the hard work you've put in; I really appreciate it, and I appreciate you sharing it with us..
ReplyDeletePostman Crack
I like your all post. You have done really good work. Thank you for the information you provide, it helped me a lot. I hope to have many more entries or so from you.
ReplyDeletehttps://licensedinfo.com/
IntelliJ IDEA
Adobe Acrobat Pro Dc
Blue-Cloner Diamond
Epubor Ultimate Converter
After looking through a few blog articles on your website,
ReplyDeletewe sincerely appreciate the way you blogged.
PDF XChange Editor Plus Crack
Maxon Cinema 4D Studio Crack
REAPER Crack
PhpStorm Crack
AVS Video Editor Crack
HMA Pro VPN Crack
ReplyDeleteWow, amazing block structure! How long
Have you written a blog before? Working on a blog seems easy.
The overview of your website is pretty good, not to mention what it does.
In the content!
vstkey.com
ACDSee Photo Studio Ultimate Crack
PhpStorm Crack
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for the informative post. download Postman
ReplyDelete