Introduction
We will see here Spring Boot Data JPA CRUD example. CRUD means Create Read Update and Delete operations. We will use in-memory h2 database in order to perform CRUD operations in database. We have other example on Spring Data JPA CRUD example but the application does not use Spring Boot. In this example, we will use Spring Boot. We will use Spring REST controller to expose our CRUD operations onto REST API.
Prerequisites
Eclipse Neon, Java 1.8, Gradle 5.4.1, Spring Boot 2.1.6
Example with Source Code
Please go through the following sections to implement Spring Boot Data JPA CRUD example.
Creating Project
We will create here gradle based project in Eclipse and the project structure will look to the similar image as shown in the below figure:

Updating Build Script
Next we will update the default generated build.gradle script to include required dependencies.
In the below build script we have included spring boot web, spring boot data jpa and h2 database. The in-memory h2 database is very useful when you need to do a quick PoC because it saves you a lots of time and effort required to setup a database.
buildscript {
ext {
springBootVersion = '2.1.6.RELEASE'
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
runtime("com.h2database:h2:1.4.196")
}
Creating Entity Class
We will work with database, where we will perform CRUD operations. Therefore we need to create entity class to map out database column with Java class attributes.
We want to store website details, such as, website id, name and URL of the website.
Another beauty of Spring Boot Data JPA starter is the below class will create the required table in the database. Even we didn’t mention any column name, so it will create same column name in the table as the Java attributes.
So the corresponding website entity class can be defined as:
package com.roytuts.spring.boot.data.jpa.crud.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Website {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String url;
public Website() {
}
public Website(Integer id, String name, String url) {
this.id = id;
this.name = name;
this.url = url;
}
//getters and setters
}
Creating VO Class
It is always good idea to create a VO or DTO class to return as a response object from REST controller instead of returning the entity class as a response object.
The VO class is also similar to the above entity class.
package com.roytuts.spring.boot.data.jpa.crud.vo;
public class WebsiteVo {
private Integer id;
private String name;
private String url;
public WebsiteVo() {
}
public WebsiteVo(Integer id, String name, String url) {
this.id = id;
this.name = name;
this.url = url;
}
//getters and setters
}
Creating Repository Interface
Spring Data JPA provides built-in methods for performing basic CRUD operations and you don’t need to write any query method.
Another beauty of Spring Data JPA is that you write Java method to query your database and Spring generates the corresponding query from your method for performing database operations.
We have just extended the JpaRepository interface but we did not write any query method inside this repository because we will use Spring’s built-in methods for performing CRUD operations.
package com.roytuts.spring.boot.data.jpa.crud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.roytuts.spring.boot.data.jpa.crud.entity.Website;
public interface WebsiteRepository extends JpaRepository<Website, Integer> {
}
Creating Service Class
The service class is used generally if you want to perform some business logic or conversion to different data.
Here in the below service method we will convert entity class to VO class using Java 8’s stream API.
We have used Java 8’s map() method to map entity to VO object.
package com.roytuts.spring.boot.data.jpa.crud.service;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.roytuts.spring.boot.data.jpa.crud.entity.Website;
import com.roytuts.spring.boot.data.jpa.crud.repository.WebsiteRepository;
import com.roytuts.spring.boot.data.jpa.crud.vo.WebsiteVo;
@Service
public class WebsiteService {
@Autowired
private WebsiteRepository repository;
public List<WebsiteVo> getWebsiteList() {
return repository.findAll().stream().map(w -> {
WebsiteVo vo = new WebsiteVo(w.getId(), w.getName(), w.getUrl());
return vo;
}).collect(Collectors.toList());
}
public WebsiteVo getWebsiteById(Integer id) {
return repository.findById(id).map(w -> {
WebsiteVo vo = new WebsiteVo(w.getId(), w.getName(), w.getUrl());
return vo;
}).orElseGet(null);
}
public void saveWebsite(WebsiteVo vo) {
Website website = new Website();
website.setName(vo.getName());
website.setUrl(vo.getUrl());
repository.save(website);
}
public void updateWebsite(WebsiteVo vo) {
Website website = new Website(vo.getId(), vo.getName(), vo.getUrl());
repository.save(website);
}
public void deleteWebsite(WebsiteVo vo) {
Website website = new Website(vo.getId(), vo.getName(), vo.getUrl());
repository.delete(website);
}
}
Creating REST Controller
Now we will expose our CRUD operations onto REST API so that any client can call our REST service and perform CRUD operations.
Exposing the operations on REST makes loosely coupled to integrate with any client technologies.
Notice how we have performed CRUD operations using the same endpoint with different HTTP methods.
package com.roytuts.spring.boot.data.jpa.crud.rest.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.roytuts.spring.boot.data.jpa.crud.service.WebsiteService;
import com.roytuts.spring.boot.data.jpa.crud.vo.WebsiteVo;
@RestController
public class WebsiteRestController {
@Autowired
private WebsiteService service;
@GetMapping("/website/{id}")
public ResponseEntity<WebsiteVo> getWebsite(@PathVariable Integer id) {
return new ResponseEntity<WebsiteVo>(service.getWebsiteById(id), HttpStatus.OK);
}
@GetMapping("/website")
public ResponseEntity<List<WebsiteVo>> getWebsiteList() {
return new ResponseEntity<List<WebsiteVo>>(service.getWebsiteList(), HttpStatus.OK);
}
@PostMapping("/website")
public ResponseEntity<String> saveWebsite(@RequestBody WebsiteVo websiteVo) {
service.saveWebsite(websiteVo);
return new ResponseEntity<String>("New website successfully saved", HttpStatus.OK);
}
@PutMapping("/website")
public ResponseEntity<String> updateWebsite(@RequestBody WebsiteVo websiteVo) {
service.updateWebsite(websiteVo);
return new ResponseEntity<String>("New website successfully updated", HttpStatus.OK);
}
@DeleteMapping("/website")
public ResponseEntity<String> deleteWebsite(@RequestBody WebsiteVo websiteVo) {
service.deleteWebsite(websiteVo);
return new ResponseEntity<String>("New website successfully deleted", HttpStatus.OK);
}
}
Creating Properties File
We will create an application.yml file that will hold some configurations. You can also create application.properties file. This file should be put under src/main/resources folder.
The below YAML or properties file contains SQL format and h2 database console enablement to see the queries executed during performing of the CRUD operations.
spring:
jpa:
show-sql: true
h2:
console:
enabled: true
Creating Main Class
Creating a main would be sufficient to deploy our application into the Tomcat server. This is a great advantage that you just need to let Spring know that it is your Spring Boot Application using @SpringBootApplication
and main class.
We also need to tell Spring where our entity class and repository interface.
package com.roytuts.spring.boot.data.jpa.crud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EntityScan("com.roytuts.spring.boot.data.jpa.crud.entity")
@EnableJpaRepositories("com.roytuts.spring.boot.data.jpa.crud.repository")
@SpringBootApplication(scanBasePackages = "com.roytuts.spring.boot.data.jpa.crud")
public class SpringBootDataJpaCrudApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootDataJpaCrudApp.class, args);
}
}
Testing the Application
Run the main class to start the application.
As we know that we don’t have any data into the database so we will first create new website and store into database.
Creating Website
Create websites using REST client as shown below:


In the console you will see below output:
Hibernate: insert into website (id, name, url) values (null, ?, ?)
Hibernate: insert into website (id, name, url) values (null, ?, ?)
Reading Websites
So when you make the below call to see list of websites then you will get below output:

You will get below output in the console:
Hibernate: select website0_.id as id1_0_, website0_.name as name2_0_, website0_.url as url3_0_ from website website0_
Updating Website
Now let’s say we want to update website with below information:

You will find console output:
Hibernate: update website set name=?, url=? where id=?
Reading a Website
Now fetch a website information by id:

So we got the website with updated information.
You will see console output:
Hibernate: select website0_.id as id1_0_0_, website0_.name as name2_0_0_, website0_.url as url3_0_0_ from website website0_ where website0_.id=?
Deleting a Website
Send below information to delete a website:

You will see below output in the console:
Hibernate: delete from website where id=?
Source Code
Thanks for reading.
Congratulations, great job, my friend.
nice work