Spring Boot JPA is a Java specification for managing relational database in Java applications. It is an Object Relational Mapping(ORM) tool which maps JAVA class property into database property. That means using spring boot JPA, we can access and persist data between Java object/ class and relational database.
This tutorial gives the clarity the process of building an application that uses spring data JPA to store and retrieve data in relational database.
We will build an application that stores Book POJOs(Plain Old Java Objects) in a memory based database.
IDE like STS, Intellij Idea, VS Code
Java17 or later
Maven3.5+
Database : MySQL
Testing environment : Postman
In MySQL environment , we created a database named as bookdb
create database bookdb
Now let’s start:
Look the project structure.
First we will set the database and JPA related information in application.properties file which is present in src/main/resources folder.
spring.datasource.url=jdbc:mysql://localhost:3306/bookdb
spring.datasource.username=root
spring.datasource.password=Silan@123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
Define a simple Book entity:
package com.silan.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name="book_detail")
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String title;
private String author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", author=" +
author + "]";
}
}
Here we have a Book class taking three attributes like id, title, author and having getXXX() and setXXX(), and having a toString() also.
Book class is annotated with @Entity, indicating that is a JPA entity and @Table, indicating that a table will create named as book_detail in MySQL database.
The Book object’s id property is annotated with @Id, so that JPA recognizes it as the object’s Id. The id property is also annotated with @GeneratedValue to indicate that the id value will generate automatically.
The convenient toString() print out the Book’s properties.
Create a repository:
Here repository is an interface that is Bookrepository which must extends JpaRepostory<Book, Integer>
By extending JpaRepository, BookRepository inherits several methods for working with Book persistence including methods for saving, deleting and finding Book entities.
Spring Data JPA also lets you define other query methods by declaring their method signature. For example, BookRepository includes the findByTitle().
package com.silan.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.silan.model.Book;
public interface BookRepository extends JpaRepository<Book, Integer>{
List<Book> findByTitle(String title);
}
Then we will create a controller component containing some handlers and we will create some end points along with PostMapping and Getmapping annotation.
Each handler method definition representing a task. That task we will test in Postman environment.
package com.silan.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.silan.model.Book;
import com.silan.repo.BookRepository;
@RestController
public class BookController {
@Autowired
BookRepository bookRepository;
@PostMapping("/books")
public String insertBook(@RequestBody Book book)
{
bookRepository.save(book);
return "record saved successfully";
}
@PostMapping("/multipleBooks")
public String insertBook(@RequestBody List<Book> book)
{
bookRepository.saveAll(book);
return "multiple records inserted successfully";
}
@GetMapping("/getAllBooks")
public List<Book> getBook()
{
return (List<Book>)bookRepository.findAll();
}
@GetMapping("/getByBookName/{name}")
public List<Book> getBookByName(@PathVariable("name")String title)
{
return (List<Book>)bookRepository.findByTitle(title);
}
}
Let’s know about some annotations used in controller component:
@RestController: Spring @RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody. This annotation is applied to a class to mark it as a request handler. Spring @RestController annotation is used to create RESTful web services using Spring MVC.
@Autowired: Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.
@PostMapping: It maps specific URLs to handler methods allowing you to receive and process data submitted through POST requests.
@GetMapping : @GetMapping annotation in Spring is a powerful for building RESTful web services. It maps HTTP GET requests to a specific handler method in Spring controllers. With the help of @GetMapping annotation we can easily define endpoints of RESTful API and handle various HTTP requests.
Then go to application class in base package.
package com.silan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaApplication.class, args);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.silan</groupId>
<artifactId>SpringBootJpaDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootJpa</name>
<description>Demo project for Spring Boot Jpa</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<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>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Now we will run the project
Right click on project or SpringBootJpaApplication.java->Run As->Spring Boot App, then we will get:
Then we will open Postman
First we will insert a record into book_detail table by posting some information
Then click on send button, we will get the following output:
Now we will check the book_detail table in MySQL database by executing select * from bookdb.book_detail
Now if we want to retrieve all records from books_detail table, then we will go through @GetMapping("/getAllBooks") for getBook().
Then we will click on send button, we will get the following output.
[
{
"id": 1,
"title": "Java Reference",
"author": "Kanetkar"
},
{
"id": 2,
"title": "Let's JAVA Programming",
"author": "Balaguruswami"
},
{
"id": 3,
"title": "Let's Python",
"author": "Denies Ritchie"
},
{
"id": 4,
"title": "Python for data science",
"author": "John De"
},
{
"id": 5,
"title": "SpringBoot by SilanTech",
"author": "Rashmi Mangaraj"
},
{
"id": 6,
"title": "JAVA SpringBoot",
"author": "Trilochan Tarai"
}
]
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc