JPA Repository is mainly used for managing the data in a Spring Boot Application.Â
We all know that Spring is considered to be a very famous framework of Java. We mainly use this Spring Boot to create the Spring-based stand-alone and production-based applications with a very minimal amount of effort.
Spring DataÂ
Spring Data is considered a Spring based programming model for accessing data. A huge amount of code is required for working with the databases, which can be easily reduced by Spring Data. It consists of multiple modules. There are many Spring applications that use JPA technology, so these development procedures can be easily simplified by Spring Data JPA.
For each of the domain entities in the application, we define a repository interface with Spring Data. A repository includes all the methods such as sorting, paginating data and CRUD operations. For specifying that the underlying interface is a repository, a marker annotation @Repository is used.
A repository is created by extending particular repository interfaces like CrudRepository, PagingOrSorting Repository, or JPARepository.
Spring Data has some advanced integrations with MVC controllers and derives dynamic query from repository method names.
JpaRepositoryÂ
JpaRepository is particularly a JPA specific extension for Repository. It has full API CrudRepository and PagingAndSortingRepository. So, basically, Jpa Repository contains the APIs for basic CRUD operations, the APIS for pagination, and the APIs for sorting.
Example of Spring Boot JPARepositoryÂ
For managing an Office entity with a JPARepository, the following Spring application is used. The following program is mainly a console program, and the data is saved in the H2 database.
Let’s check out the structure of our project:
pom.xml
src
├───main
│  ├───java
│  │  └───com
│  │    └───springBootJPARepository
│  │      │  Application.java
│  │      │  MyRunner.java
│  │      ├───model
│  │      │    Office.java
│  │      └───repository
│  │          OfficeRepository.java
│  └───resources
│      application.properties
└───test
    └───java
The following code is for the build file of Maven. For using Spring Data JPA with Hibernate, the spring-boot-starter-data is a starter.
Now let us go through the flow of the code of pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootJPARepository</groupId>
    <artifactId>springbootjparepository</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
The application.properties file is considered to be the main Spring Boot configuration file. The Spring banner is turned off with the spring.main.banner-mode property.
For the console, the logging pattern is defined with logging.pattern.console.
Below is code for resources/application.properties:
spring.main.banner-mode=off
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-7p) %clr(%logger{0}){blue} %clr(%m){faint}%n
Now let’s check out the office entity. It consists attributes like office_id, office_name and no_of_employees.
Here is the code for com/springBootJPARepository/model/Office.java.
package com.springBootJPARepository.model;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "offices")
public class Office {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long office_id;
    private String office_name;
    private int no_of_employees;
    public Office() {
    }
    public Office(String office_name, int no_of_employees) {
        this.office_name = office_name;
        this.no_of_employees = no_of_employees;
    }
    public Long getOffice_id() {
        return office_id;
    }
    public void setId(Long office_id) {
        this.office_id = office_id;
    }
    public String getOffice_name() {
        return office_name;
    }
    public void setOffice_name(String office_name) {
        this.office_name = office_name;
    }
    public int getNo_of_employees() {
        return no_of_employees;
    }
    public void setNo_of_employees(int no_of_employees) {
        this.no_of_employees = no_of_employees;
    }
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + Objects.hashCode(this.office_id);
        hash = 79 * hash + Objects.hashCode(this.office_name);
        hash = 79 * hash + this.no_of_employees;
        return hash;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Office other = (Office) obj;
        if (this.no_of_employees != other.no_of_employees) {
            return false;
        }
        if (!Objects.equals(this.office_name, other.office_name)) {
            return false;
        }
        return Objects.equals(this.office_id, other.office_id);
    }
    @Override
    public String toString() {
        var builder = new StringBuilder();
        builder.append("Office{id=").append(office_id).append(", office_name=")
                .append(office_name).append(", no_of_employees=")
                .append(no_of_employees).append("}");
        return builder.toString();
    }
}
From the JPARepository, the OfficeRepository gets extended; the type of entity and the type of primary key are provided by this repository.
Now let us check out the code for OfficeRepository.java which is in com/springBootJPARepository/repository/OfficeRepository.java:
package com.springBootJPARepository.repository;
import com.springBootJPARepository.model.Office;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OfficeRepository extends JpaRepository<City, Long> {
}
The various methods of JPARepository are used in MyRunner.java
Let us check out the code in com/springBootJPARepository/MyRunner.java
package com.springBootJPARepository;
import com.springBootJPARepository.model.Office;
import com.springBootJPARepository.repository.OfficeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
@Component
public class MyRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);
    @Autowired
    private OfficeRepository OfficeRepository;
    @Override
    public void run(String... args) throws Exception {
        OfficeRepository.save(new Office("A COMPNAY", 432000));
        OfficeRepository.save(new Office("B COMPANY", 1759000));
        OfficeRepository.save(new Office("C COMPANY", 1280000));
        OfficeRepository.save(new Office("D COMPANY", 1748000));
        OfficeRepository.save(new Office("E COMPANY", 3971000));
        OfficeRepository.save(new Office("F COMPANY", 8550000));
        OfficeRepository.save(new Office("G COMPANY", 464000));
        logger.info("# of offices: {}", OfficeRepository.count());
        logger.info("All offices unsorted:");
        var offices = OfficeRepository.findAll();
        logger.info("{}", offices);
        logger.info("------------------------");
        logger.info("All offices sorted by name_of_office in descending order");
        var sortedoffices = OfficeRepository.findAll(Sort.by(Sort.Direction.DESC, "name_of_office"));
        logger.info("{}", sortedoffices);
        logger.info("------------------------");
        logger.info("Deleting all offices");
        OfficeRepository.deleteAllInBatch();
        logger.info("# of offices: {}", OfficeRepository.count());
    }
}
We then inject the OfficeRepocitory into the OfficeRepository field.
@Autowired
private OfficeRepository OfficeRepository;
With save(), a new office is inserted:
officeRepository.save(new Office("A COMPANY", 432000));
With count(), the number of cities are counted:
logger.info("# of offices: {}", officeRepository.count());
For getting all the offices, findAll() method is generally used:
logger.info("All offices unsorted:");
var offices = officeRepository.findAll();
logger.info("{}", offices);
To the findAll(), a sort object is passed so that we can get all the names of the cities in descending order:
logger.info("All offices sorted by name_of_office in descending order");
var sortedoffices = cityRepository.findAll(Sort.by(Sort.Direction.DESC, "name_of_office"));
logger.info("{}", sortedoffices);
In a batch, all the cities can be deleted by us using deleteAllInBatch().
logger.info("Deleting all offices");
officeRepository.deleteAllInBatch();
The spring boot application is set up by the Spring Boot Application.
Let’s first check out the code for com/springBootJPARepository/Application.java
package com.springBootJPARepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;Â
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}Â
Output
...
22-02-15 Tue 12:47:14.593 INFOÂ MyRunner # of offices: 7
22-02-15 Tue 12:47:14.593 INFOÂ MyRunner All offices unsorted:
22-02-15 Tue 12:47:14.652 INFOÂ MyRunner [Office{id_of_office=1, name_of_office=A COMPANY, population=432000}, Office{id_of_office=2, name_of_office=B COMPANY, population=1759000}, Office{id_of_office=3, name_of_office=C COMPANY, population=1280000}, Office{id_of_office=4, name_of_office=D COMPANY, population=1748000}, City{id_of_office=5, name_of_office=E COMPANY, population=3971000}, City{id_of_office=6, name_of_office=F COMPANY, population=8550000}, City{id_of_office=7, name_of_office=G COMPANY, population=464000}]
22-02-15 Tue 12:47:14.652 INFOÂ MyRunner ------------------------
22-02-15 Tue 12:47:14.652 INFOÂ MyRunner All offices sorted by name_of_office in descending order
22-02-15 Tue 12:47:14.667 INFOÂ MyRunner [City{id_of_office=7, name_of_office=G COMPANY, population=1748000}, City{id_of_office=6, name_of_office=F COMPANY, population=1280000}, City{id_of_office=5, name_of_office=E COMPANY, population=8550000}, City{id_of_office=4, name_of_office=D COMPANY, population=3971000}, City{id_of_office=3, name_of_office=C COMPANY, population=464000}, City{id_of_office=2, name_of_office=B COMPANY, population=1759000}, City{id_of_office=1, name_of_office=A COMPANY, population=432000}]
22-02-15 Tue 12:47:14.668 INFOÂ MyRunner ------------------------
22-02-15 Tue 12:47:14.668 INFOÂ MyRunner Deleting all offices
22-02-15 Tue 12:47:14.681 INFOÂ MyRunner # of offices: 0
...
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!
ConclusionÂ
In this article, we discovered how we can manage our application with JpaRepository.
As we know, these days along with the knowledge of data structure and algorithms, development skill is also tested by recruiters while hiring. A techie should therefore be closely conversant with all the technologies being used by companies and keep track of the latest developments and trends of the tech industry. There are some full stack development courses offered by Simplilearn you can check out for upgrading your skill set. This program will give you the foundation for building full stack web apps using the Java programming language. You'll begin with the basics of JavaScript, and then venture into some of the more advanced concepts like Angular, Spring Boot, Hibernate, JSPs, and MVC.
Another such platform is SkillUp where all of the self-learning courses are free of cost, so you can explore and learn in-demand skills in different domains of your choice such as Machine Learning, Artificial Intelligence, business analytics etc. on your schedule.
Enroll in one of these programs to enhance your skills and become industry-ready.