Skip to content

  • Home
  • Core Java
    • Write Your Own Immutable Class In Java
    • Write Your Own Singleton Class In java
    • Java Concurrent Package
    • Java Stream Revisited
    • Print odd and even numbers using thread
    • SOLID principles
    • Comparable Vs Comparator
    • Sort HashMap/TreeMap based on value
    • Deep and Shallow Copy in Java with examples
    • Find the frequency of each character in a String
    • How to avoid duplicate Employee objects in HashSet ?
  • Spring
    • Loose Coupling & Dependency Injection
    • Bean Scope
    • Spring Bean Lifecycle
    • IoC Container Vs Application Context Vs Bean Factory
    • @Component Vs @Service @Repository Vs @Controller
    • How to read properties file in Spring
    • Spring AOP (Aspect Oriented Programming)
    • @Component Vs @Bean in Spring
    • Exception Handling in SpringBoot
    • XML configuration Vs Annotations configuration in Spring
    • Spring Data JPA
    • Spring Data REST
  • Spring Security
    • Spring Security with Form, Basic and JWT
    • Security Configuration in Spring Boot Apps
    • Security Protocols & Frameworks
    • Okta OAuth 2.0 SSO with Springboot
    • Spring Boot 2.x Security using Username Password
    • Spring Boot 2.x Security using JWT
    • Spring Boot 3.x Security using Username Password
    • Spring Boot 3.x Security using JWT
  • Microservices
    • Spring Cloud Config (Server & Client)
    • Spring Boot Microservices Tutorial (Part 1 of 2)
    • Spring Boot Microservices Tutorial (Part 2 of 2)
    • Circuit Breaker – Resilience4j
    • The Twelve-Factor App Principles
  • Event Driven Microservices
    • What is Event Driven Microservice ?
    • What is Saga Design Pattern ?
    • What is CQRS Design Pattern ?
  • Spring AI
    • ChatGPT API + SpringBoot Integration
  • Hibernate & JPA
    • JPA vs JDBC
    • CRUD Example Using Spring Boot JPA + H2 + Gradle
    • MongoDB Atlas With Spring Boot Example
    • Transaction Management
    • Relationships in JPA & Hibernate
    • Hibernate First & Second Level Cache
    • Spring Boot Flyway Postgres
  • DevOps
    • What is Devops ?
    • Docker
    • Kubernetes (K8S)
    • Jenkins
    • Infrastructure As Code
  • Functional Programming
    • Functional Programming Vs Structured Programming
    • Java 8 Programs For Interview
    • Predicate, Function, Consumer and Supplier in Java 8
    • Sort a List having Employee objects using Java 8
    • Find Employee from List using Java 8
  • AWS
    • AWS S3
    • AWS EC2
    • EC2 Solutions Architecting
    • How to create an EC2 instance ?
    • How to connect to AWS EC2 instance ?
    • Deploy application to AWS
    • AWS Lambda Java Tutorial
    • Spring Cloud Functions
    • How to Start/Stop AWS ECS automatically using Java Spring?
    • Container Solution in AWS
    • AWS SQS, SNS, MQ and Kinesis
    • Databases in AWS
    • AWS VPC: Peering, Endpoint, VPN, Gateways- Internet, NAT, DX
    • Machine Learning in AWS
    • Storage Solutions in AWS
    • AWS ASG (Auto Scaling Group)
  • AWS Certifications
    • SAA-C03
      • Design Cost-Optimized Architectures
    • AWS Certified Solution Architect-Associate
      • Question 1
  • Kafka
    • Apache Kafka
    • Kafka Producer & Consumer Example Using Spring boot & Conduktor
  • Angular
    • Angular Tutorial – Part 1
    • Angular Tutorial – Part 2
  • Miscellaneous
    • How to add a project to Git/GitHub/GitLab
    • How to Clone a project from Git/GitLab using Git Bash
    • How to query Oracle tables based on some date ?
    • How to highlight text in WordPress ?
    • How to add Page Jumps in WordPress page ?
  • Interview Preparation
    • Core java interview questions
    • Java Threads Interview Questions
  • Contact Me
  • Toggle search form

CRUD Example Using Spring Boot JPA + H2 + Gradle

In this tutorial we will demo a Spring Boot CRUD application using REST + Spring Boot JPA + H2 + Gradle.

Create a spring boot project with below dependencies:

build.gradle:

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.h2database:h2'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

application.properties:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.data.jpa.repositories.bootstrap-mode=default

Model class:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Person {
	@Id
	@GeneratedValue
	private int id;
	private String name;
	private Integer age;
}

Repository:

@Repository
public interface MyRepository extends CrudRepository<Person,String>{
}

Service class:

@Service
public class MyService {
	@Autowired
    MyRepository myRepository;

	public Iterable<Person> getPersons() {
		return myRepository.findAll();
	}

	public Person addPerson(Person person) {
        return myRepository.save(person);
    }

	public Person updatePerson(Person person, String id) {
		Person person2 = myRepository.findById(id).get();
		person2.setName(person.getName());
		person2.setAge(person.getAge());

		return myRepository.save(person2);
	}

	public Person getPersonById(String id) {
		Person person = myRepository.findById(id).get();
		return person;
	}

	public void deletePerson(String id) {
		myRepository.deleteById(id);
	}
}

Controller class:

@RestController
@CrossOrigin(origins="http://localhost:4200/")
@RequestMapping("/api")
public class MyController {
	@Autowired
	MyService myService;

	@GetMapping("/getPersons")
	public Iterable<Person> getPersons() {
		return myService.getPersons();
	}
	
	@PostMapping("/addPerson")
    //@ResponseStatus(HttpStatus.CREATED)
    public Person addPerson(@RequestBody Person person){
        return myService.addPerson(person);
    }

	@PutMapping("/updatePerson/{id}")
	public Person updatePerson(@RequestBody Person person, @PathVariable String id){
		return myService.updatePerson(person,id);
	}

	@GetMapping("getPersonById/{id}")
	public Person getPersonById(@PathVariable String id){
		return myService.getPersonById(id);
	}

	@DeleteMapping("/deletePerson/{id}")
	public void deletePerson(@PathVariable String id) {
		myService.deletePerson(id);
	}
}

Now start the application.
Do a POST call to below url with the below request:

http://localhost:8080/api/addPerson

{
    "name": "Prasanna Kumar",
    "age": 46
}

Here is the screenshot for the same:

To see the DB console: http://localhost:8080/h2-console

Hit “Connect” without any password.
You will land up in the console. There you can see all the tables:

Similarly you can test other API endpoints for – GET, PUT and DELETE operations.

Source code of the above example is here: https://github.com/heapsteep/ReST

If you want to know how to create a Spring Boot ReST with MongoDB click here.

Copyright © 2025 .

Powered by PressBook Blog WordPress theme