Spring Boot JPA CRUD Example (2024)
In this tutorial, we'll demonstrate how to create a Spring Boot CRUD application + MYSQL with below rest api's.
POST
- Create Employee RecordGET
- List all employeesGET
- Get employees by it's idPUT
- Update/Edit selected employee detailsDELETE
- Remove selected employee recordDELETE
- RemoveAll employees.
Also Refer Spring Boot Audit Logging Example to automatically store auditing information for each entity, such as created by, created date, modified by, and modified date using JPA.
Create Spring Boot application
Create Spring Boot application from Spring Initializr.
Project Structure
Add Dependencies
Add below dependencies for Web - spring-boot-starter-web
, JPA - spring-boot-starter-data-jpa
and MYSQL - mysql-connector-java
in pom.xml
.
<?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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-jpa-mysql-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-jpa-mysql-example</name>
<description>Spring Boot + JPA + MYSQL CRUD Example</description>
<properties>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Take a look at our suggested posts:
Application Properties
Add database connection details in application.properties
file.
spring.datasource.url=jdbc:mysql://localhost/employeetestdb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.initialization-mode=always
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
# spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
Data Model
Create Employee
class, contains id
, name
and
role
.
package com.techgeeknext.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "name")
private String name;
@Column(name = "role")
private String role;
}
JPA Repository
Create EmployeeRepository
interface that extends JpaRepository
.
package com.techgeeknext.repository;
import com.techgeeknext.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Employee Controller to handle CRUD rest endpoints
package com.techgeeknext.controller;
import com.techgeeknext.model.Employee;
import com.techgeeknext.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;
import java.util.Optional;
//@CrossOrigin(origins = "http://localhost:3000") //open for specific port
@CrossOrigin() // open for all ports
@RestController
public class EmployeeController {
@Autowired
EmployeeRepository employeeRepository;
/**
* Get all the employees
*
* @return ResponseEntity
*/
@GetMapping("/employees")
public ResponseEntity<List<Employee>> getEmployees() {
try {
return new ResponseEntity<>(employeeRepository.findAll(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Get the employee by id
*
* @param id
* @return ResponseEntity
*/
@GetMapping("/employee/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") long id) {
try {
//check if employee exist in database
Employee empObj = getEmpRec(id);
if (empObj != null) {
return new ResponseEntity<>(empObj, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Create new employee
*
* @param employee
* @return ResponseEntity
*/
@PostMapping("/employee")
public ResponseEntity<Employee> newEmployee(@RequestBody Employee employee) {
Employee newEmployee = employeeRepository
.save(Employee.builder()
.name(employee.getName())
.role(employee.getRole())
.build());
return new ResponseEntity<>(newEmployee, HttpStatus.OK);
}
/**
* Update Employee record by using it's id
*
* @param id
* @param employee
* @return
*/
@PutMapping("/employee/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable("id") long id, @RequestBody Employee employee) {
//check if employee exist in database
Employee empObj = getEmpRec(id);
if (empObj != null) {
empObj.setName(employee.getName());
empObj.setRole(employee.getRole());
return new ResponseEntity<>(employeeRepository.save(empObj), HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
/**
* Delete Employee by Id
*
* @param id
* @return ResponseEntity
*/
@DeleteMapping("/employee/{id}")
public ResponseEntity<HttpStatus> deleteEmployeeById(@PathVariable("id") long id) {
try {
//check if employee exist in database
Employee emp = getEmpRec(id);
if (emp != null) {
employeeRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Delete all employees
*
* @return ResponseEntity
*/
@DeleteMapping("/employees")
public ResponseEntity<HttpStatus> deleteAllEmployees() {
try {
employeeRepository.deleteAll();
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Method to get the employee record by id
*
* @param id
* @return Employee
*/
private Employee getEmpRec(long id) {
Optional<Employee> empObj = employeeRepository.findById(id);
if (empObj.isPresent()) {
return empObj.get();
}
return null;
}
}
Test Spring Boot JPA CRUD Example
- Start the Spring Boot Application by running
spring-boot:run
or by running main class. Create New Employee
Open Postman, use POST method with end point http://localhost:8080/employee and provide Employee details to create new employee record.List Employees
Use GET method with end point http://localhost:8080/employees to get all employees.Get Employee
Use GET method with end point http://localhost:8080/employee/1 to get employee by id.Edit Employee
Use PUT method with end point http://localhost:8080/employee/1 where 1 is the id of the employee and provide employee details as body in Postman to edit.Delete Employee
Use DELETE method with end point http://localhost:8080/employee/1 where 1 is the id of the employee.Delete All Employees
Use DELETE method with end point http://localhost:8080/employees to delete all employees records from database.
Refer React Crud Example for front end crud implementation.
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot JPA CRUD Example