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

Spring Data JPA

Spring Data JPA is one of the module of Spring Data umbrella framework. In this tutorial we will be using it along with Spring Data REST for creating a Save operations on a MySQL database. The other Spring Data modules which we are not going to cover here are: Spring-Data-Redis, Spring-Data-Mongo, etc..

Why to use Spring Data JPA instead of Hibernate?

This is not an alternative to Hibernate, rather we use it in tandem with Hibernate or any other ORM framework.

Benefit of Spring Data JPA ?

It reduces a lot of boiler plate code of a traditional DAO layer. A developer’s job should be to concentrate more on the business logic rather than getting involved with technical complexity and boiler plate code. So basically there are 3 reasons of using Spring Data JPA:

  1. No-code repository.
  2. No boiler plate code.
  3. Generated queries.


Some points to remember:

  • Spring Data JPA is not an implementation of JPA.
  • Spring Data JPA is an Add-on to JPA.
  • Spring Data JPA brings in a concept called- repositories. Which is a set of interfaces which define query methods. This acts as a DAO abstraction layer.

So, lets start….

We will be using Spring Boot for this.
Lets create a spring boot application either by spring initializr or by using below wizard in eclipse:

Lets give it a name: SpringDataJPAMySQL

Choose respective dependencies:

Hit Finish.

Finally you would be seeing below maven dependencies in your project:

                <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

Please note that we had not added spring-boot-starter-data-rest dependency, but still we will be calling this application by a REST call.

Lets have our classes.

In application.properties add the below entires for MySQL:

## Spring DATASOURCE (DataSourceAutoConfiguration &amp; DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/heapsteep?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true&amp;useSSL=false
spring.datasource.username = root
spring.datasource.password = root


## Hibernate Properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

Book.java:

package com.heapsteep.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Setter @Getter
@Entity
@Table(name = "books")
public class Book {
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private int isbn;
    private String name;
}

BookRepository.java:

package com.heapsteep.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.heapsteep.model.Book;

@Repository
public interface BookRepository extends JpaRepository<Book, Long>{

}

BookController.java:

package com.heapsteep.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.heapsteep.model.Book;
import com.heapsteep.repository.BookRepository;

@RestController
@RequestMapping("/api")
public class BookController {
	@Autowired
    BookRepository bookRepository;

    @GetMapping("/books")
    public List<Book> getAllNotes() {
        return bookRepository.findAll();
    }

    @PostMapping("/books")
    public Book createNote(@Valid @RequestBody Book book) {
        return bookRepository.save(book);
    }


}

SpringDataJpaMySqlApplication.java:

package com.heapsteep;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
public class SpringDataJpaMySqlApplication {

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

}

Thats it…

Right click on the SpringDataJpaMySqlApplication.java file and run as Java application.

Open a REST client (Postman/SOAPUI) and call below URL with below json input parameters:
http://localhost:8080/api/books

{
     "isbn" : 123,
     "name" : "Book name 1"
 }

[P.S.] When copying the above json code, first copy it to a Notepad++ file and check the double quotes format. Otherwise you may get error: JSON parse error: Invalid UTF-8…

You will get below response:

{
    "id": 1,
    "isbn": 123,
    "name": "Book name 1"
 }

Below is the full screenshot of the SOAPUI tool:

You can login to MySQL and see the table – books is been created and 1 record is being inserted into it.

GitHub URL for the above code:
https://github.com/heapsteep/springboot-jpa-mysql.git

Copyright © 2025 .

Powered by PressBook Blog WordPress theme