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

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 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.
  • 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.


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;

@Table(name = "job")
public class Job {
 @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

Create an Exception Class

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


public class ResourceNotFoundException extends Exception{

 public ResourceNotFoundException(String 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>


import org.springframework.stereotype.Repository;

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.


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

import javax.transaction.Transactional;

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


public class JobService {

 private JobRepository jobRepository;
  * Post into H2 database
 public Job saveJob(Job 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();
   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 {


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.


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;


public class JobController {

 private JobService jobService;
 public List<Job> getAllJobs(){
  return jobService.getJobs();
 // request body covert json object to java obj
 public ResponseEntity<Job> saveJob(@RequestBody Job job){
  return new ResponseEntity<Job>(jobService.saveJob(job),HttpStatus.CREATED);
 public ResponseEntity<Job> updateJobs(@RequestBody Job job, @PathVariable("id") long id) throws ResourceNotFoundException{
  return new ResponseEntity<Job>(jobService.updateJob(job),HttpStatus.CREATED);
 public ResponseEntity<String> deleteJobs(@PathVariable("id") long id) throws ResourceNotFoundException{
  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 and click on Run as Spring Boot App.


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

public class SpringBootH2DatabaseApplication {

 public static void main(String[] args) {, 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.