Spring Boot CRUD Operation using in-memory database example

 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 hereSpring 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.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enabling the H2 console
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:h2:C:/data/crudoperation

 
# Custom H2 Console URL
spring.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
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    
    @Bean
    public 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
@Table
public class Employee {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String firstname;

    @Column
    private String lastname;

    @Column
    private LocalDate dob;

    @Column
    private 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;

@Repository
public interface EmployeeRepositoory extends CrudRepository<EmployeeLong> {

}

Next Step. Create service interface.

package com.bce.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.bce.model.Employee;

@Service
public interface EmployeeService {

    void saveOrUpdate(Employee employee);

    List<EmployeegetAllEmployee();

    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;

@Service
public class ServiceImpl implements EmployeeService {

    @Autowired
    EmployeeRepositoory employeeRepositoory;

    @Override
    public void saveOrUpdate(Employee employee) {
        employeeRepositoory.save(employee);
    }

    @Override
    public List<EmployeegetAllEmployee() {
        return (List<Employee>) employeeRepositoory.findAll();

    }

    @Override
    public Employee getEmployeeById(long id) {

        return employeeRepositoory.findById(id).get();
    }

    @Override
    public 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;

@RestController
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @PostMapping("/employee")
    public void saveEmployee(@RequestBody Employee employee) {
        employeeService.saveOrUpdate(employee);
    }

    @GetMapping("/employee")
    public List<EmployeefindAll() {
        return employeeService.getAllEmployee();
    }

    @DeleteMapping("/employee/{id}")
    public ResponseEntity<StringdeleteEmployee(@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<StringupdateEmployee(@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.


1. Create Records API Testing.



2. Get records API testing.



3. Check records In DB:




Download Code from GitHub.  Source Code




No comments:

Post a Comment