1. Create a Spring boot application
Spring Boot provides a web tool called Spring Initializer to create 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: springboot-backend.demo
Packaging: Jar
Java : 8
Download Spring Boot project as a zip file, unzip it, and import it into IntelliJ IDEA.
2. open your project demo into IntelliJ IDEA
3. Configure MySQL Database
Don’t forget to change the spring.datasource.username and spring.datasource.password as per your MySQL installation. Also, create a database named whatever you want in MySQL before proceeding to the next section.
spring.datasource.url=jdbc:mysql://localhost:3306/gestionemployees?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto = update
You don’t need to create any tables. The tables will automatically be created by Hibernate from the Employee
entity that we will define in the next step. This is made possible by the property spring.jpa.hibernate.ddl-auto = update
4. Create JPA Entity
Go to model package, create a class named Employee and add the following content into it:
package net.javaguides.springboot.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import jakarta.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String lastName;
@Column(name = "email")
private String emailId;
}
- Create Spring Data JPA Repository
package repository;
import model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
// all crud database methods
}
- Create ResourceNotFoundException Custom Exception
package 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 controller;
import model.Employee;
import 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 exception.ResourceNotFoundException;
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);
}
}
8. Running the Application
We have successfully developed all the CRUD Rest APIs for the Employee model. Now it's time to deploy our application in a servlet container(embedded tomcat).
Two ways we can start the standalone Spring boot application.
- From the root directory of the application and type the following command to run it -
mvn spring-boot:run
Top comments (0)