EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot JPA
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot JPA

Spring Boot JPA

Definition of Spring Boot JPA

In Spring boot we have JPA which makes the mapping of Java object to the relational database. By the use of it, we can perform so many operations on the database and get the desired result we want. Spring boot framework gives us starter JPA dependency which contains all the required things, by the help of this we can able to perform and connect to the database easily. JPA is a set of interface which follows the ORM approach which stands for object -relation mapping, By the help of JPA we are able to persist and access the data or java object between the application and relational database. As the database is a very important part when it comes to storage of data and performed the transaction on those data. In the coming section of the tutorial, we will see how we can configure the JPA in the spring boot application to interact with the relation database and see the usage as well for better understating.

Syntax:

As we know that to access the JPA we need to make some configuration in our application, the most command used annotation in spring boot is mention below, it is a basic configuration that we need, let’s take a closer look at the syntax for better understating to see below;

@SpringBootApplication
@EnableJpaRepositories
public class name_Application{}

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As you can see we have used @EnableJpaRepositories to enable the JPA use inside the project. Also, we will have to look at the practice syntax to make use of JPA in, see below;

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

e.g. :

@SpringBootApplication
@EnableJpaRepositories
public class DemoApplication{}

In the coming section of the tutorial, we will what are the other configurations which need to in place in order to run the spring boot application in JPA easily and without error.

How Spring boot JPA works?

As we already know that in order to make the JPA work, we have to make some configuration also we need to add the dependency as well. JPA is basically used to have the interaction between the java classes and the database. By the use of this, we are able to store the values inside the database and fetch them when needed. First, let’s start with the lifecycle of the JPA by the steps which are described below;

1) NULL: First the object is in the null state, which means it is not associate with entityManager, Reference see below code:

e.g. :

Demo demo = null;

2) NEW: This is the second stage for the JPA object when we create the object using the new operator, but still entityManager does not exist.

e.g:

Demo demo = new Demo();

3) Managed: In this stage, the object we have created will be managed by the entityManager, so we will do some coding to register it inside the entityManager, by using the following code;

e.g.:

entityManager.getTransaction().begin();
Demo demo = new Demo();
entityManager.persist(demo);
entityManager.getTransaction().commit();

Here we have configured our object to entityManager now the entityManager will manage the object for us.

4) Detached: This state detaches means to remove the object from the entityManager. For reference see below;

e.g. :

entityManager.detach(demo);

5) Remove: This stage will help us to remove the object from the database.

e.g.:

entityManager.removed(myObject);

Below see the flow chart diagram for the life cycle stage of the JPA for better understanding;

Spring Boot JPA

Examples

1. In this example, we will see the saving of a simple object inside the database. For that we have created the entity, service, repository to store the object, also we have added the dependency inside the pom.xml as well.

Example:

a) create the project from the scratch by using the spring initializer link mention below;

URL: https://start.spring.io/

Spring Boot JPA 1

b) Add the below dependency also while creating the JPA example: without his, we will not be able to use the JPA features inside our application so it is required. You can directly type this name in the spring initializer and it will add this dependency for you.

e.g:

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

c) Create the entity class like below; this will be the entity class that is going to store in the db., also later we can perform many operations on it like, fetch, delete, update, etc. based on the requirement.

@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "city")
private String city;
}

d) now create the JPA repository to save the student object inside it, this is an interface and very important because through this only all the transactions will take place. @Repository annotation is required here, so we can autowired it later to make use of it.

e.g.:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java. time.LocalDateTime;
import java.util.List;
@Repository
public interface StudentRepository extends JpaRepository<Student, String> {
}

e) Now one method inside the service class and auto wired the repository inside it to call the JPA methods to save the object.

e.g.:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java. time.LocalDateTime;
import java.util.List;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public void create(Student student){
studentRepository.save(student);
}
}

f) Now final step to make the configuration work, in the main application class of the project see below for reference;

e.g.:

package com. test.Traders;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableJpaRepositories
public class StudentApplication{
public static void main(String[] args){
}SpringApplication.run(StudentApplication.class, args);
}

g) Now run the above code and you will see below output; if the JPA is configured properly in the application and try to save object using any rest client, for that ad the controller as well, with a simple endpoint.

Output:

Spring Boot JPA 2

Spring Boot JPA 3

Conclusion

JPA is very easy to use and handle because spring boot makes this simple for us. We just need to do the little configuration after that we can use it, to store and retrieve our entity object from the database, we can follow the above steps to make this work in the spring boot application.

Recommended Articles

This is a guide to Spring Boot JPA. Here we discuss Definition, syntax, How Spring boot JPA works? examples with code implementation. You may also have a look at the following articles to learn more –

  1. Spring Boot Profiles
  2. Spring Boot Path Variable
  3. Spring Boot Dependencies
  4. Spring Boot Repository
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more