CRUD Operations in Spring Boot using REST API, H2 Database and Spring Data JPA

CRUD(Create, Read, Update, Delete) Operations in Spring Boot using REST API, H2 Database, and Spring Data JPA. In this article, we will be creating RESTFul API with Spring Boot P, H2 Database, and Spring Data JPA. If you want to create REST API with Spring Boot, MySQL Database and Spring Data JPA check this article https://codebun.com/crud-operation-in-spring-boot-using-restapi/.

The only difference here is that we will be using H2 Database instead of MYSQL Database. So, let us understand what is H2 Database is.

What is H2 Database?

H2 Database is an in-memory database that we will use at runtime. It is written in Java. It has also a pretty simple configuration.

To use this database in a spring boot application, just add the h2 database dependency and that’s it. This database is initialized when your application is in startup mode and will be destroyed when the application is stopped.

We can also access the console of the h2 database from the web: Just hit the localhost:8888/h2.

REST API Methods

Some of the basic RestAPI methods that will use in these examples i.e  GET, POST, PUT and DELETE and the meaning of these methods are too simple as the name suggests.

Following are the methods available in  REST API CRUD.

  • GET: To read a resource.
  • POST: To add a resource.
  • PUT: To update a resource.
  • DELETE: To delete a resource.

For example, to get a resource present on the web, we will just use the HTTP method GET. To create a resource, we will call the POST method and so on.

CRUD REST API with Spring Boot, H2 database, and Spring Data JPA

Step 1: Open IDE STS- Spring Tool Suite

Step 2: Go to File > Spring Starter Project.

Step 3: Now, Fill all the fields as shown below and click Next.

Step 4: Now, Add the dependencies such as Spring Web Dependency, H2 database, Lombok and Spring Data JPA click Next > Finish.

Once the project is created, create the folder structure as shown below

Configure application. properties file

This is the file provided by spring boot to configure H2 database. Also, configure JPA-related information.

#port number
server.port=8888

spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
  • server.port is set to 8888.
  • spring.h2.console.enabled is set to true to enable console for H2 Database.
  • spring.h2.console.path is set to /h2 which signifies that path at which console is available.
  • spring.jpa.hibernate.ddl-auto is set to update so that whatever changes we will do will be reflected in the schema.
  • spring.jpa.show-sql is set to true to show SQL generated by the Hibernate.

Create an Entity Class

Here, we will create an Entity that would be mapped to the database tables. It is nothing but the Java POJO class.

Job.java

package com.abc.h2.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Table(name = "job")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Job {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private long id;
 private String jobName;
 private String jobDescription;
 private String jobLocation;
 private String jobType;
}
  • @Entity is used to annotate the classes to indicate that they are JPA entities.
  • @Table annotation is used to specify the name of the table that should be mapped with entities.
  • @Id annotation is used for the primary key.
  • I have used the Lombok library to remove boilerplate code. In case you want to know what is Lombok check this article https://codedec.com/tutorials/how-to-configure-lombok-into-eclipse/

Create an Exception Class

If the resource is not found this exception will be thrown.

package com.abc.h2.exception;

public class ResourceNotFoundException extends Exception{

 public ResourceNotFoundException(String msg) {
  super(msg);
 }
}

Create Repository Interface

The repository here is the DAO layer, which performs all the database operations. JobRepository interface is created which will extends JPARepository<ClassName, ID>

JobRepository.java

package com.abc.h2.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.abc.h2.model.Job;
public interface JobRepository extends JpaRepository<Job, Long> {

}

Create a Service Layer

This layer is responsible to handle business logic. Here, we will create the JobService class.

JobService.java

package com.abc.h2.service;

import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.abc.h2.exception.ResourceNotFoundException;
import com.abc.h2.model.Job;
import com.abc.h2.repository.JobRepository;

@Service
@Transactional
public class JobService {

 @Autowired
 private JobRepository jobRepository;
 
 /*
  * Post into H2 database
  */
 public Job saveJob(Job job) {
  return jobRepository.save(job);		
 }
 
 /*
  * Get List from H2 db
  */
 public List<Job> getJobs(){
  return jobRepository.findAll();
 }
 /*
  * Update Job in H2 DB
  */
 
 public Job updateJob(Job job) throws ResourceNotFoundException {
  Optional<Job> job_new = jobRepository.findById(job.getId());
  if(!job_new.isPresent()) {
   throw new ResourceNotFoundException("Resource Not Found!!!!");
   
  }else {
   Job job2 = job_new.get();
   job2.setJobDescription(job.getJobDescription());
   job2.setId(job.getId());
   job2.setJobLocation(job.getJobLocation());
   job2.setJobName(job.getJobName());
   job2.setJobType(job.getJobType());
   jobRepository.save(job2);
   return job2;
  }
  
 }
 /*
  * Get Job By id from H2 DB
  */
 public Job getJobById(long id) throws ResourceNotFoundException {
  Optional<Job> job_new = jobRepository.findById(id);
  if(!job_new.isPresent()) {
   throw new ResourceNotFoundException("Resource Not Found!!!!");
  }else {
   return job_new.get();
  }
  
 }
 /*
  * Delete Job
  */
 public void deleteJob(long id) throws ResourceNotFoundException {
  Optional<Job> job_new = jobRepository.findById(id);
  if(!job_new.isPresent()) {
   throw new ResourceNotFoundException("Resource Not Found!!!!");
  }else {
   jobRepository.delete(job_new.get());
  }

 }
}

Create a Controller

The client request is sent to the controller which acts as an API layer that will have the endpoints for REST API.

JobController.java

package com.abc.h2.controller;

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.abc.h2.exception.ResourceNotFoundException;
import com.abc.h2.model.Job;
import com.abc.h2.service.JobService;

@RestController
public class JobController {

 @Autowired
 private JobService jobService;
 @GetMapping("/jobs")
 public List<Job> getAllJobs(){
  return jobService.getJobs();
 }
 // request body covert json object to java obj
 @PostMapping("/jobs")
 public ResponseEntity<Job> saveJob(@RequestBody Job job){
  return new ResponseEntity<Job>(jobService.saveJob(job),HttpStatus.CREATED);
 }
 
 @PutMapping("/jobs/{id}")
 public ResponseEntity<Job> updateJobs(@RequestBody Job job, @PathVariable("id") long id) throws ResourceNotFoundException{
  job.setId(id);
  return new ResponseEntity<Job>(jobService.updateJob(job),HttpStatus.CREATED);
 }
 
 @DeleteMapping("/jobs/{id}")
 public ResponseEntity<String> deleteJobs(@PathVariable("id") long id) throws ResourceNotFoundException{
  jobService.deleteJob(id);
  return new ResponseEntity<String>("Deleted",HttpStatus.OK);
  
 }
}
  • Mark this class as @RestController(It is used to simplify the creation of REST APIs).
  • The @GETMapping is used to map HTTP GET requests on specific handler methods.
  • The @POSTMapping is used to map HTTP POST requests on specific handler methods.
  • The @PUTMapping is used to map HTTP PUT requests on specific handler methods.
  • The @DELETEMapping is used to map HTTP DELETE requests on specific handler methods.
  • The @ResponseEntity represents an HTTP response.
  • The @RequestBody is used to convert JSON to Java objects.

Following are the REST endpoints:

Run the Application

Now, open the SpringBootH2DatabaseApplication.java and click on Run as Spring Boot App.

package com.abc.h2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootH2DatabaseApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringBootH2DatabaseApplication.class, args);
 }

}

Test the Application

Now, we will use the POSTMAN Application to test the APIs. Make sure you have POSTMAN installed on your machine.

Test Post Request

Test Get Request

Test Put Request

Test Delete Request

In this way, we learned how to create CRUD REST APIs with Spring Boot, H2 database, and Spring Data JPA.