What is Spring Data JPA?

Last Updated : 06 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JPA is a Java specification(Jakarta Persistence API) and it manages relational data in Java applications. To access and persist data between Java object(Plain Old Java object)/ class and relational database, we can use JPA. Upon  Object-Relation Mapping (ORM), it follows the mechanisms. It has the runtime EntityManager API and it is responsible for processing queries and transactions on the Java objects against the database. The main highlight is it uses JPQL (Java Persistent Query Language) which is platform-independent. JPA mainly covers persistence in terms of 

  • The Java Persistence API
  • Object-Relational metadata
  • Moreover under the persistence package API is defined.
  • We cannot say that JPA is a framework, but It defines a concept and it can be implemented by any framework.

Advantages of Using JPA

  • No need to write DDL/DML queries, instead we can map by using XML/annotations.
  • JPQL is used and since it is platform-independent, we no need to depend on any native SQL table. Complex expressions and filtering expressions are all handled via JPQL only.
  • Entity can be partially stored in one database like MySQL and the rest can be in Graph database Management System.
  • Dynamic generation of queries is possible.
  • Integration with Spring framework is easier with a custom namespace.

Units comprised in JPA are available under javax persistence package:

Persistence It has static methods to obtain an EntityManagerFactory instance
EntityManagerFactory Factory class for EntityManager and responsible for managing multiple instances of EntityManager
EntityManager It is an interface that works for the Query instance
Entity They are persistent objects and stored as records in the database
Persistence Unit Set of all entity classes
EntityTransaction It has one-to-one relationship with EntityManager.
Query To get relation objects that meet the criteria.

Many have a confusion between JPA and HIbernate. Let us see few key differences

JPA

Hibernate

JPA : It is a Java specification for mapping relational data in Java application. It is not a framework
 
Hibernate is an ORM framework and in that way data persistence is possible.
In JPA, no implementation classes are provided.
 
In Hibernate, implementation classes are provided.
Main advantage is It uses JPQL (Java Persistence Query Language)  and it is platform-independent query language.
 
Here it is using HQL (Hibernate Query Language).
It is available under javax.persistence package. 
 
It is available under org.hibernate package.
In Hibernate, EclipseLink, etc. we can see its implementation.
 
Hibernate is the provider of JPA.
Persistence of data is handled by EntityManager. Persistence of data is handled by Session.

Let us see a sample application for a spring boot application with JPA.

Example Project

It is a maven-driven project

Project Structure:

Project Structure

 

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         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>2.3.0.BUILD-SNAPSHOT</version>
        <relativePath/> 
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-data-jpa-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-data-jpa-example</name>
    <description>Demo project for Spring Boot</description>
  
    <properties>
        <java.version>1.8</java.version>
    </properties>
  
    <dependencies>
      <!-- Spring Boot provides starter dependency spring-boot-starter-data-jpa 
            to connect Spring Boot application with relational database efficiently.
           This is the mandatory one -->
        <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>
         
          <!-- In memory database called apache derby is used 
                It is based on Java,JDBC and SQL standards
                Spring boot can auto configure with derby-->
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <!-- For testcase execution in spring boot project -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
  
</project>


Let us see the key important files in the project. Starting with POJO class

GeekUserRecord.java

Java




import javax.persistence.Entity;
import javax.persistence.Id;
  
// It should be marked as Entity,
@Entity
public class GeekUserRecord {
    // Required attributes are given here. This will
    // comprise as collection of columns of a table
    @Id // For Primary key
    private int id;
    private String name;
    private String email;
    private String gender;
    private int numberOfPosts;
  
    // Getter and setter methods
    public String getGender() { return gender; }
  
    public void setGender(String gender)
    {
        this.gender = gender;
    }
  
    public int getNumberOfPosts() { return numberOfPosts; }
  
    public void setNumberOfPosts(int numberOfPosts)
    {
        this.numberOfPosts = numberOfPosts;
    }
  
    // default constructor is mandatory to specify
    public GeekUserRecord() {}
  
    public int getId() { return id; }
  
    public void setId(int id) { this.id = id; }
  
    public String getName() { return name; }
  
    public void setName(String name) { this.name = name; }
  
    public String getEmail() { return email; }
  
    public void setEmail(String email)
    {
        this.email = email;
    }
}


Let us see the controller file now

GeekUserController.java

Java




import com.gfg.model.GeekUserRecord;
import com.gfg.service.GeekUserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
  
// RestController = combination of the @Controller and the
// @ResponseBody It provides the response in the form of JSON
// or XML
@RestController
public class GeekUserController {
    
    @Autowired private GeekUserService userService;
    
    // To get all geekusers
    @RequestMapping("/")
    public List<GeekUserRecord> getAllUser()
    {
        return userService.getAllGeekUsers();
    }
    
    // To add a geekuser, this is needed
    @RequestMapping(value = "/add-geekuser",
                    method = RequestMethod.POST)
    public void
    addUser(@RequestBody GeekUserRecord userRecord)
    {
        userService.addGeekUser(userRecord);
    }
}


Let us see the service file

GeekUserService.java

Java




import com.gfg.model.GeekUserRecord;
import com.gfg.repository.GeekUserRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
@Service
public class GeekUserService {
    
    @Autowired
    private GeekUserRepository geekUserRepository;
    
    // for getting all the geekusers, we need to write this
    // method and output is GeekUserRecord as a list,
    public List<GeekUserRecord> getAllGeekUsers()
    {
        List<GeekUserRecord> geekUserRecords
            = new ArrayList<>();
        geekUserRepository.findAll().forEach(
            geekUserRecords::add);
        return geekUserRecords;
    }
    
    // While adding a geekuser, we need to save that
    public void addGeekUser(GeekUserRecord userRecord)
    {
        geekUserRepository.save(userRecord);
    }
}


We need to add a repository file and it should extend CrudRepository

GeekUserRepository.java

Java




import com.gfg.model.GeekUserRecord;
import org.springframework.data.repository.CrudRepository;
  
public interface GeekUserRepository
    extends CrudRepository<GeekUserRecord, String> {
}


Now, we need to execute this program and check the output. For that, we need to run the below file

SpringDataJPAExampleApplication.java

Java




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
  
@SpringBootApplication
public class SpringDataJPAExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDataJPAExampleApplication.class, args);
    }
}


Right-click on the file and run the file as a Java application, we can see the output in the console.

Output:

Output

The server started at port 8080

Initially as there are no records, when we hit http://localhost:8080, we wont be seeing any data. Let’s add the data by adding via the Postman client. Postman client has to be installed for doing this operation. URL to add users: http://localhost:8080/add-geekuser (Remember that this URL matches the controller file requestmapping).

Output

 

Now a user is added. Hence we can verify the same by using http://localhost:8080

 

If we check with the added user detail and display user detail, they are same. If we have added more than 1 record, those records also will be displayed. In the whole project, we have not seen anywhere about the SQL statement like Insert(for adding)/Select(for retrieving). We need to have a POJO class. We have to possess the code with the important annotations as mentioned in the code. Automatically JPA (Java Persistence API) will take care of it.



Previous Article
Next Article

Similar Reads

Difference between JPA and Spring Data JPA
JPA provides specifications for persisting, reading, and maintaining data from Java objects to relational tables in a database. The JPA defines rules and principles for conducting standard interfaces. Spring data repository significantly reduces the extra code necessary to provide a data access layer for multiple persistence stores. Spring Data JPA
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
Spring Data JPA vs Spring JDBC Template
In this article, we will learn about the difference between Spring Data JPA vs Spring JDBC Template. Spring Data JPATo implement JPA-based repositories, Spring Data JPA, a piece of the Spring Data family, takes out the complexity. With the help of spring data JPA the process of creating Spring-powered applications that support data access technolog
5 min read
Spring Boot Batch Processing Using Spring Data JPA to CSV File
The Spring Batch is a framework in the Spring Boot ecosystem It can provide a lot of functionalities for Batch processing. The Spring Batch framework simplifies the batch development of applications by providing reliable components and other patterns for common batch processing concerns. Mostly, batch processing is used to read and write data in bu
7 min read
Show SQL from Spring Data JPA/Hibernate in Spring Boot
In Spring Boot, Spring Data JPA is part of the larger Spring Data Project that can simplify the development of the data access layers in the spring applications using the Java Persistence API and it can provide a higher-level abstraction over the JPA API. It can reduce the boilerplate code and make it easier to work with the database. Spring Data J
6 min read
Spring Boot - Spring Data JPA
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any java object directly into a database table. Usually, the name of the object being persisted becomes the name of the table, and each field within tha
6 min read
Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
We will be running the SQL scripts with Spring JDBC +JPA + HSQLDB. These scripts are used to perform SQL commands at the time of application start. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. JPA is just a specification that faci
3 min read
Spring Data JPA - Insert Data in MySQL Table
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Data JPA - @Table Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Data JPA - @Id Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring Data JPA - @Column Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
2 min read
Spring Data JPA - Attributes of @Column Annotation with Example
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring Data JPA - Delete Records From MySQL
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Data JPA - Find Records From MySQL
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Data JPA @Query Annotation with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. @Query Annotation is used for defining custom queries in Spring Data JPA. When you are unable to use the
7 min read
findBy Methods in Spring Data JPA Repositories
Spring Data JPA abstracts the boilerplate code required to interact with the database, allowing developers to focus more on business logic rather than database connectivity and query formation. The findBy() method, in particular, is a part of the repository layer in Spring Data JPA, enabling developers to construct queries simply by defining method
5 min read
Spring Data JPA - @Modifying Annotation
@Modifying annotation in Spring Data JPA allows modification queries such as update and delete and enhances the capabilities of the @Query annotation. It enables data transformation actions beyond simple data retrieval, ensuring transaction integrity and improving performance. The @Modifying annotation is used to enhance the @Query annotation so th
4 min read
Optimizing Performance with Spring Data JPA
Optimizing Performance in Spring Data JPA is crucial for developing efficient, scalable, and responsive applications. Spring Data JPA simplifies database interactions in Java applications by providing a repository-based approach to data persistence. Performance optimization with Spring Data JPA is crucial for ensuring that your application runs eff
5 min read
Derived Query Methods in Spring Data JPA Repositories
Spring Data JPA helps manage database operations in Java applications with ease. One powerful feature is derived query methods, which let you perform common database queries by just naming the method. This way, you don’t have to write complex SQL or JPQL queries manually. Instead, you can use simple method names to search, sort, and filter your dat
6 min read
Pagination and Sorting with Spring Data JPA
Pagination and sorting are crucial features when dealing with large datasets in applications. They can help to break down into manageable chunks and provide a way to order the data according to specific criteria. In the Spring Boot application using Spring Data JPA, we can easily implement these features to enhance the performance and user experien
5 min read
Enabling Transaction Locks in Spring Data JPA
Transaction locks in Spring Data JPA can help manage concurrent data access. It can ensure the data consistency. By controlling how transactions acquire the locks on the database rows or tables, we can prevent issues such as lost updates and ensure that the application maintains data integrity. This article will guide you through enabling the trans
7 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
8 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot JPA Sample Maven Project With Query Methods
In this article, let us see a sample maven project in Spring Boot JPA with Query methods. Spring Boot + JPA removes the boilerplate code and it will be enhanced much if we use query methods as well. Let us discuss this project with MySQL Connectivity for geeksforgeeks database and table name as "Contest". Sample Project MySQL scripts: -- if we want
6 min read
Spring Boot JPA Native Query with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. A native query is a SQL statement that is specific to a particular database like MySQL. It varies a litt
7 min read
How to Set the Schema Name Dynamically in Spring JPA?
Spring JPA provides a convenient way to save Java objects to relational databases. However, it typically assumes that you have a single schema for your database. If you need to work with multiple schemas, you can use a custom naming strategy to set the schema name dynamically. Creating a Custom Naming StrategyTo create a custom naming strategy, you
3 min read
Spring Boot - Build a Dynamic Full Text Search API Using JPA Queries
A Global Full-Text Entity Search is a search functionality that allows users to find entities such as records or objects within a dataset by searching through the entirety of their content. Global Full-Text Entity Search is like having a super-smart search companion that digs deep into the entire content of entities. Consider the below examples to
9 min read
Spring Boot - Database Integration (JPA, Hibernate, MySQL, H2)
In modern application development, integrating a database is crucial for persisting and managing data. Spring Boot simplifies this process by providing seamless integration with various databases through JPA (Java Persistence API) and Hibernate ORM (Object-Relational Mapping). This article will guide you through setting up database integration in a
7 min read
Article Tags :
Practice Tags :