Spring Boot CRUD API Operations using IN-Memory Database Examples
Purpose: In this post, we will learn how we can add In-Memory Database and perform the CRUD Operations. The steps are given below.
1. Setup and Create Project: Visit here. Spring Boot Rest API Hello World Examples.
Next Step. Spring Boot Parent Dependencies.
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.M1</version><relativePath /> <!-- lookup parent from repository --></parent>
Next Step. Swagger Dependencies.
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency>
Next Step. In-memory database dependency
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
Next Step. Database configuration in application.properties
spring.datasource.driverClassName=org.h2.Driverspring.datasource.username=saspring.datasource.password=spring.jpa.database-platform=org.hibernate.dialect.H2Dialect#enabling the H2 consolespring.h2.console.enabled=truespring.jpa.show-sql=truespring.jpa.generate-ddl=truespring.jpa.hibernate.ddl-auto=updatespring.datasource.url=jdbc:h2:C:/data/crudoperation# Custom H2 Console URLspring.h2.console.path=/h2
Next Step. Spring Boot main class.
Class: Application.java
Note: @SpringBootApplication=@Configuration+ @EnableAutoConfiguration+ @ComponentScan.
package com.bce;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;@SpringBootApplication@EnableSwagger2public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();}}
Next Step. Create model.
package com.bce.model;import java.time.LocalDate;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@Tablepublic class Employee {@Id@Column@GeneratedValue(strategy = GenerationType.AUTO)private Long id;@Columnprivate String firstname;@Columnprivate String lastname;@Columnprivate LocalDate dob;@Columnprivate String email;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getFirstname() {return firstname;}public void setFirstname(String firstname) {this.firstname = firstname;}public String getLastname() {return lastname;}public void setLastname(String lastname) {this.lastname = lastname;}public LocalDate getDob() {return dob;}public void setDob(LocalDate dob) {this.dob = dob;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}
Next Step. Create Repository.
package com.bce.repository;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository;import com.bce.model.Employee;@Repositorypublic interface EmployeeRepositoory extends CrudRepository<Employee, Long> {}
Next Step. Create service interface.
package com.bce.service;import java.util.List;import org.springframework.stereotype.Service;import com.bce.model.Employee;@Servicepublic interface EmployeeService {void saveOrUpdate(Employee employee);List<Employee> getAllEmployee();Employee getEmployeeById(long id);void delete(long id);}
Next Step. Create service implementation.
package com.bce.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.bce.model.Employee;import com.bce.repository.EmployeeRepositoory;import com.bce.service.EmployeeService;@Servicepublic class ServiceImpl implements EmployeeService {@AutowiredEmployeeRepositoory employeeRepositoory;@Overridepublic void saveOrUpdate(Employee employee) {employeeRepositoory.save(employee);}@Overridepublic List<Employee> getAllEmployee() {return (List<Employee>) employeeRepositoory.findAll();}@Overridepublic Employee getEmployeeById(long id) {return employeeRepositoory.findById(id).get();}@Overridepublic void delete(long id) {employeeRepositoory.deleteById(id);}}
Next Step. Create Rest Controller.
package com.bce.controller;import java.time.LocalDate;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;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.RestController;import com.bce.exceptions.EmployeeNotFoundException;import com.bce.model.Employee;import com.bce.service.EmployeeService;@RestControllerpublic class EmployeeController {@AutowiredEmployeeService employeeService;@PostMapping("/employee")public void saveEmployee(@RequestBody Employee employee) {employeeService.saveOrUpdate(employee);}@GetMapping("/employee")public List<Employee> findAll() {return employeeService.getAllEmployee();}@DeleteMapping("/employee/{id}")public ResponseEntity<String> deleteEmployee(@PathVariable long id) {@SuppressWarnings("unused")Employee employee;try {employee = employeeService.getEmployeeById(id);} catch (Exception e) {throw new EmployeeNotFoundException();}employeeService.delete(id);return new ResponseEntity<>("Employee deleted successfully", HttpStatus.OK);}@PutMapping("/employee/{id}/{dob}")public ResponseEntity<String> updateEmployee(@PathVariable long id, @PathVariable String dob) {Employee employee;try {employee = employeeService.getEmployeeById(id);} catch (Exception e) {throw new EmployeeNotFoundException();}employee.setDob(LocalDate.parse(dob));employee.setId(id);employeeService.saveOrUpdate(employee);return new ResponseEntity<>("Employee updated succesfully", HttpStatus.OK);}}
Next Step. Server Port: The default server port is 8080. Wish you want to change open application.properties and add the below line.
server.port=8081
Next Step: Open H2 in memory database in browser.
Next Step: Test with swagger. Open given below URL on the browser.
2. Get records API testing.
3. Check records In DB:
Download Code from GitHub. Source Code
No comments:
Post a Comment