☛ SpringBoot CRUD Rest API with Spring Data JPA

in this blog, creating custom rest API. Rest API that means use Rest Controller @RestController on Configuration class. for the view, we use the Postman tool . where we testing our request and response generated by URL. Here showing the development process one by one.

HTTP Method Url Mapping CRUD Action
POST localhost:1235/code4devops/api/employee Create a new employee
GET localhost:1235/code4devops/api/employees Read a list of employees
GET localhost:1235/code4devops/api/employee/{employeeId} Read a single employee
PUT localhost:1235/code4devops/api/employee Update an exiting employee
DELETE localhost:1235/code4devops/api/employee/{employeeId} Delete an existing employee

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.code4devops</groupId>
	<artifactId>jpacrud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>jpacrud</name>
	<description>project for Spring Boot</description>
	<!-- lookup parent from repository -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/> 
	</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>

Note: write some database information in appliction.properties

appliction.properties

# JDBC properties
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3306/springbootshweta?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto=update
# show the hibernate query in sql format
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
server.servlet.context-path=/code4devops
server.port=1235

Employee.java

package com.code4devops.entity;
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 = "employee_jpa")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", length = 10, nullable = false)
	private int id;
	@Column(name = "customer_fname", length = 45, nullable = true)
	private String firstName;
	@Column(name = "last_name", length = 45, nullable = true)
	private String lastName;
	@Column(name = "email", length = 45, nullable = true)
	private String email;
	@Column(name = "mobile", length = 45, nullable = true)
	private String mobile;
	@Column(name = "aadhar_number", length = 45, nullable = true)
	private String aadharNumber;
	
	public Employee() {}
	
	public Employee(int id, String firstName, String lastName, String email, String mobile, String aadharNumber) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.mobile = mobile;
		this.aadharNumber = aadharNumber;
	}

	//create getter and setter for all Instance Variable

	@Override
	public String toString() {
		return id + " " + firstName + " " + lastName + " " + email+ " " + mobile + " " + aadharNumber;
	}
}

EmployeeDAO.java

package com.code4devops.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.code4devops.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}

EmployeeService.java

 
package com.code4devops.service;
import java.util.List;
import com.code4devops.entity.Employee;
public interface EmployeeService {
	public List<Employee> findAll();
	public Employee findById(int theId);
	public void save(Employee theEmployee);
	public void deleteById(int theId);
}

EmployeeServiceImpl.java

package com.code4devops.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.code4devops.dao.EmployeeRepository;
import com.code4devops.entity.Employee;

@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeRepository employeeRepository;
	
	@Override
	public List<Employee> findAll() {
		return employeeRepository.findAll();
	}
	@Override
	public Employee findById(int theId) {
		Optional<Employee> result = employeeRepository.findById(theId);
		Employee theEmployee = null;
		if (result.isPresent())
			theEmployee = result.get();
		else
			throw new RuntimeException("Did not find employee id - " + theId);
		return theEmployee;
	}
	@Override
	public void save(Employee theEmployee) {
		employeeRepository.save(theEmployee);
	}
	@Override
	public void deleteById(int theId) {
		employeeRepository.deleteById(theId);
	}

}

EmployeeController.java

package com.code4devops.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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 com.code4devops.entity.Employee;
import com.code4devops.service.EmployeeService;

@RestController
@RequestMapping("/api")
public class EmployeeController {

	@Autowired
	private EmployeeService employeeService;
		
	@GetMapping("/employees")
	public List findAll() {
		return employeeService.findAll();
	}

	@GetMapping("/employee/{employeeId}")
	public Employee getEmployee(@PathVariable int employeeId) {
		Employee theEmployee = employeeService.findById(employeeId);
		if (theEmployee == null)
			throw new RuntimeException("Employee id not found - " + employeeId);
		return theEmployee;
	}
	
	@PostMapping("/employee")
	public Employee addEmployee(@RequestBody Employee theEmployee) {
		theEmployee.setId(0);
		employeeService.save(theEmployee);
		return theEmployee;
	}
	
	@PutMapping("/employee")
	public Employee updateEmployee(@RequestBody Employee theEmployee) {
		employeeService.save(theEmployee);
		return theEmployee;
	}
	
	@DeleteMapping("/employee/{employeeId}")
	public String deleteEmployee(@PathVariable int employeeId) {
		Employee tempEmployee = employeeService.findById(employeeId);
		if (tempEmployee == null) 
			throw new RuntimeException("Employee id not found - " + employeeId);
		employeeService.deleteById(employeeId);
		return "Deleted employee id - " + employeeId;
	}
	
}

Application.java

package com.code4devops;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
{
    "firstName":"Ashutosh",
    "lastName":"Mishra",
    "email":"ashumishra9015@gmail.com",
    "mobile":"9560822035",
    "aadharNumber":"ASH123DDF5435SDFF"
}

{
    "id":12,
    "firstName":"Ashu",
    "lastName":"Mishra",
    "email":"ashumishra5@gmail.com",
    "mobile":"9560822032",
    "aadharNumber":"2ASH1DDF5435SDFF"
}