springboot application

Basic Spring Boot CRUD Operations(Maven + H2 + Hibernate) with an Example (Step by Step Guide)

CRUD is the basic level of Operations in an application. So here you learn about the CRUD operations (End-To-End) in Spring Boot. Let us get into that deeply now.

Post this CRUD Operations tutorial you will have a clear picture of how to coordinate with Maven + Spring Boot + JPA (Hibernate) linkings and these you understand practically.

What are all pre-requisites for Spring Boot CRUD Operations :

  • Create Maven Dependencies
  • Create Java Classes(Model + Controller + Services + DAO)
  • Repository Class (For JPA Operations)
  • Configure Application Properties

That’s it you are ready to go.

First We need to set up the Pom.xml.

spring-boot-starter-data-jpa
Configuring dependencies is the first step in Spring Boot Application as it imports all the relevant Jars into the path. For the CRUD operations, we need to configure the dependency as spring-boot-starter-data-JPA. This will import all the necessary jars for Spring Data, JPA API, and JPA Impletementation Hibernate such as for the CRUD operation.

h2
To configure the H2 Database, no external database needs not to be configured. H2 Console details to be enabled in the application.properties

Next is to import the dependency for JPA Repository, Database Dependencies

Create the Required Model Classes

Here we need to create the Model Class Employee.java with all the relevant fields. empId, empName, empJoinedDate, empExperience.

Things to note before creating a model is to add the relevant annotations against the relevant fields, for CRUD Operations we need to set the @Entity, @Table, @Column, @id annotations, These annotations will map the java variables with Database Entity, Tables, and Columns.

EmployeeEntity.java

package com.example.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="EMPLOYEE")
public class EmployeeEntity {
 
    @Id
    @GeneratedValue
    private Long empId;
     
    public Long getEmpId() {
		return empId;
	}

	public void setEmpId(Long empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public int getEmpExperience() {
		return empExperience;
	}

	public void setEmpExperience(int empExperience) {
		this.empExperience = empExperience;
	}

	public Date getEmpJoinedDate() {
		return empJoinedDate;
	}

	public void setEmpJoinedDate(Date empJoinedDate) {
		this.empJoinedDate = empJoinedDate;
	}

	@Column(name="empName")
    private String empName;
     
    @Column(name="empExperience")
    private int empExperience;
 
    @Column(name="empJoinedDate")
    private Date empJoinedDate;
    
    //@Column(name="mail", nullable=false, length=200)
     
    @Override
    public String toString() {
        return "Employee [employeeId=" + empId + ", empExperience=" + empExperience + 
                ", empJoinedDate=" + empJoinedDate + ", empName=" + empName  + "]";
    }
}

Create the Controller Class

In our scenario, we are going to add, fetch, update, delete operations against the Employee table. To do these we need to have a controller with the relevant methods. These methods will be invoked through the Rest URL with the relevant path mentioned.

Things to Note :
Since we are using the Rest Operations, we need to use all the necessary Rest Annotation to make the controller Rest Based. Annotations are

@RestController – To configure the class as Rest based Controller
@GetMapping – Receive the incoming request by the path provided for Fetch Operation
@PostMapping – Receive the incoming request by the path provided for Insert Operation
@DeleteMapping – Receive the incoming request by the path provided for Delete Operation
@PutMapping – Receive the incoming request by the path provided for Update Operation

EmployeeContrller.java

package com.example.springboot;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.EmployeeEntity;
import com.example.service.EmployeeService;
 
@RestController
@RequestMapping("/employees")
public class EmployeeController 
{
    @Autowired
    EmployeeService service;
 
    @GetMapping
    public ResponseEntity<List<EmployeeEntity>> getAllEmployees() {
        List<EmployeeEntity> list = service.getAllEmployees();
 
        return new ResponseEntity<List<EmployeeEntity>>(list, new HttpHeaders(), HttpStatus.OK);
    }
 
    @GetMapping("/{id}")
    public ResponseEntity<EmployeeEntity> getEmployeeById(@PathVariable("id") Long id) 
                                                    throws Exception {
    	Logging.info("Fetch Request Received :"+id);
    	EmployeeEntity entity = service.getEmployeeById(id);
 
        return new ResponseEntity<EmployeeEntity>(entity, new HttpHeaders(), HttpStatus.OK);
    }
 
    @PostMapping
    public ResponseEntity<EmployeeEntity> createOrUpdateEmployee(@RequestBody EmployeeEntity employee)
                                                    throws Exception {
    	Logging.info("Inserting Request Received");
        EmployeeEntity updated = service.createOrUpdateEmployee(employee);
        return new ResponseEntity<EmployeeEntity>(updated, new HttpHeaders(), HttpStatus.OK);
    }
 
    @DeleteMapping("/{id}")
    public HttpStatus deleteEmployeeById(@PathVariable("id") Long id) 
                                                    throws Exception {
        service.deleteEmployeeById(id);
        return HttpStatus.FORBIDDEN;
    }
 
}

Create the Service Class :

The service class is the subsequent place to do the Controller Operations, all operations mentioned in the Controlled are properly executed here. So in the scenario, we need to have a few basic annotations to be mentioned in the service class.

@Service – The place to do the Business Logic

EmployeeService.java

package com.example.service;


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import com.example.model.EmployeeEntity;
import com.example.repository.EmployeeRepository;
import com.example.springboot.Logging;

@ComponentScan 
@Service
public class EmployeeService {
     
    @Autowired
    EmployeeRepository repository;
     
    public List<EmployeeEntity> getAllEmployees()
    {
        List<EmployeeEntity> employeeList = repository.findAll();
         
        if(employeeList.size() > 0) {
            return employeeList;
        } else {
            return new ArrayList<EmployeeEntity>();
        }
    }
     
    public EmployeeEntity getEmployeeById(Long id) throws Exception 
    {
        Optional<EmployeeEntity> employee = repository.findById(id);
         
        if(employee.isPresent()) {
            return employee.get();
        } else {
            throw new Exception("Employee Not Present to Fetch");
        }
    }
     
    public EmployeeEntity createOrUpdateEmployee(EmployeeEntity entity) throws Exception 
    {
        
    	Logging.info(" New Record : "+entity.toString());
    	Optional<EmployeeEntity> employee = repository.findById(entity.getEmpId());
        
    	Logging.info("Before inserting New Record");
        
        if(employee.isPresent()) 
        {
            EmployeeEntity newEntity = employee.get();
            newEntity.setEmpName(entity.getEmpName());
            newEntity.setEmpExperience(entity.getEmpExperience());
            newEntity.setEmpJoinedDate(entity.getEmpJoinedDate());
            newEntity = repository.save(newEntity); // To update the Recod into the table
            Logging.info("Existing Record Updated ");
            return newEntity;
        } else {
            entity = repository.save(entity);
            Logging.info("New Record Inserted ");
            return entity;
        }
        
        
    } 
     
    public void deleteEmployeeById(Long id) throws Exception 
    {
        Optional<EmployeeEntity> employee = repository.findById(id);
         
        if(employee.isPresent()) 
        {
            repository.deleteById(id);
        } else {
            throw new Exception("No employee available to Delete");
        }
    } 
}

Create the Repository Class :

Repository Class is used to link with Database Layer.

Spring Boot has a default Interface named CrudRepository from the package org.springframework.data.repository, This interface is the base for CRUD operations in Spring Boot. This interface offers plenty of inbuilt methods needed for CRUD Operations.

Syntax for CrudRepository :

public interface CrudRepository extends Repository

Here Repository is the Spring Data Repository Interface.

Example :

public Interface ItemInterface extends CrudRepository
{
}

In the above example, we have created one Interface which extends the CrudRepository Interface and mentions the Repository named Item. Also, provided the type of the Id for that repository.

JpaRepository :

Root Package of JpaRepository is org.springframework.data.jpa.repository, JpaRepository extends CrudRepository

  • Flushing Methods
  • Batch Based Operation methods
  • Persistence Context

Learn Some basic differences between CrudRepository and JpaRepository here.

EmployeeRepository.java

package com.example.repository;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.model.EmployeeEntity;
@ComponentScan
@Repository
public interface EmployeeRepository 
        extends JpaRepository<EmployeeEntity, Long> {
 
}

Configure Application.properties

application.properties

spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=test
spring.datasource.password=test
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 
# Enabling H2 Console
spring.h2.console.enabled=true
 
# Custom H2 Console URL
spring.h2.console.path=/h2-console
 
# create database schema from SQL files
spring.jpa.hibernate.ddl-auto=none
 
#Turn Statistics on and log SQL stmts
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.generate_statistics=false

Run the Application

Run the Main Class. it will invoke the run() method from the SpringApplication class. Once the service is up. Now it’s time to set up the H2 Database, this database can be accessed with the H2 Console.

springboot run

Setting Up H2 Console

http://localhost:8080/h2-console is to open the Console for the application. So here you have two things to do. The first is to create the Table name that you have mentioned on the Entity Class.

The second is to create the DB Sequence for the Primary key.

That’s it from the H2 Console side. Now you are fine with setup. Execute the program now.

h2 console spring boot ihbernate
h2 console delete record
h2 console creating sequences springboot example

Test the Application :

We have created the application for Add, Delete, Update, Fetch Operations. We are using Postman to test the Application

Adding the Record through Rest Service :

Type: POST
Path: http://localhost:8080/employees/
Operation: Insert/Update the Record into the table.

add record spring boot example
add record spring boot example with h2 database

Read the Record through Rest Service :

Type: GET
Path:http://localhost:8080/employees/1
Operation: Read the Record from the table.

view record spring boot example

Update the Record through Rest Service :

Type: DELETE
Path:http://localhost:8080/employees/1
Operation: Delete the Record from the table and provides the status with FORBIDDEN.

update record spring boot example
update record spring boot example

Delete the Record through Rest Service:

Type: DELETE
Path:http://localhost:8080/employees/1
Operation: Delete the Record from the table and provides the status with FORBIDDEN.

delete_record spring_boot example

Conclusion :

Learning Spring Boot will be always interesting and engaging. Learning CRUD Operations with Spring Makes you more interactive with Spring Boot. Hope you enjoyed
the tutorial.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *