What is Spring Data JPA? Spring Data JPA in spring boot example

Imran Shaikh
1

In this tutorial, I will explain to you what is JPA and Spring Data JPA. I will also walk you through how to use spring data JPA using the spring boot framework, and I'm sure you will enjoy learning Spring Data JPA.

What is Spring Data JPA? Spring Data JPA in spring boot example
toc

Prerequisite


1. How to build rest API using Spring boot
2. Java 8 or later, I'll use Amazon corretto 11
3. Maven

What is JPA?


JPA stands for Java Persistence API.


JPA is the collection of the Methods and the classes to communicate with the data into the relational database.


JPA was designed and developed by the Oracle corporation under the Open source API Licence. Many vendors such as Eclipse, Redhat Spring launch there own JPA framework by manipulating open source JPA.


Some of the most well-liked JPA API on the top of the Oracle JPA flavor are Hibernate, Eclipselink, Spring Data JPA, etc.



What is Spring Data JPA?


Spring Data JPA is a layer on top of the Oracle open source JPA API. Spring Data JPA is designed for the developer to focus on the business logic rather on boilerplate code.


Two reasons to use Spring Data JPA

Spring Data Jpa provide the two most eye-catching feature to adopt over the other JPA flavors such as Hibernate, EclipseLink, etc.


Reduce the boilerplate code - No DAO implementation

The first, most beneficial feature for the developer which they would enjoy is the spring data JPA reduce the boilerplate code.


The Spring Data JPA internally very smartly handles some CRUD operation code to communicate with the relational database by implementing the repository interface. So the developer should focus on the business logic.


 @Repository
 public interface BooksRepository extends JpaRepository {}

In the above example, As you can see, we have not created the BooksRepositoryImpl class for the CRUD operation code to trigger the Database queries, because we have extends JpaRepository which handle all the simple CRUD operation query.


Generate Query with a method name

The Spring Data JPA provider very handly feature of querying the relational database using the method name. This mean Spring Data JPA can fire some basic query with the method name.


 @Repository
 public interface BooksRepository extends JpaRepository 
 {
     public List findByAuthor(String author);
 }

The Spring Data JPA is capable of querying the database using a method name, but it can handle only some basic queries. The method name format should be like the findBy and followed by the @Entity field name or Database column name.


Some example would be, findByTitle(String title); findByPrice(long price); etc.


Repository in the Spring Data JPA


The Spring Data JPA provides the three repositories which are the interface in java to deal with the relational database and they are as follows


  1. CrudRepository
  2. JpaRepository
  3. PagingAndSortingRepository

How to setup Spring Data JPA in the Spring Boot?


We will be building the Rest API using the spring boot framework and for the database, we will use the H2 in-memory database with the spring data JPA.


Project Structure

Spring Data JPA project structure

pom.xml

Just add the following dependencies in the pom.xml for integrating the spring data JPA working with the in-memory H2 database.


 <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>

application.properties

Sometimes we need to configure the setting in the framework to work with it. The spring boot provides two various types of file base configuration such as application.properties and application.yml.


In this tutorial, we will use application.properties. Add the following configuration in the application.properties file.


 # Enabling h2 console
 spring.h2.console.enabled = true
            
 # Configuring in memory h2 database
 spring.datasource.platform = h2
 spring.datasource.url = jdbc:h2:mem:learnjavaskills
 spring.datasource.username = learnjavaskills.in
 spring.datasource.password = 123456

Explanation of the above application.properties

In this example, we are using the in-memory H2 database, which means our data will exist until the application is live.


we can access the in-memory database by using the following URL.


http://localhost:8080/h2-console(code-box)

However by default, this console is disabled, so to enable the H2 database console, we need to override some spring boot default properties. Following is the way of enabling the H2 database console.


spring.h2.console.enabled = true(code-box)

And after enabling the h2 console, we have configured H2 Database.


Entity

Let's create a Books entity for persistently store or manipulate the data into the relational database.


Create a Books class and past the following code. This Book class is a simple POJO in java.


 package in.learnjavaskills.springdataJPAtutorila.dto;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
            
 @Entity
 public class Books 
 {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
                    
    @Column(name = "title")
    private String title;
                    
    @Column(name = "author")
    private String author;
                            
    public Long getId() {
    return id;
    }
                
    public void setId(Long 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 "Books [id=" + id + ","
                             + " title="
                             + title 
                             + ", author=" 
                             + author + "]";
    }
 }

Annotations explains

  1. The @Entity annotation in the Spring Data JPA indicates that the class is an entity for persistently store or manipulate the data into the relational database.

  2. @Id, To create a primary key in the relational database use @Id before the variable declaration.

  3. The @GeneratedValue(strategy=GenerationType.AUTO) annotation is for auto increment the primary key. The increment starts from the 1 and it will increment values by 1.

  4. @Column(name = "title") annotation is used of relational databse table name.
(alert-passed)

data.sql

The in-memory database flushes all the data when you shut down your application. Isn't it a headache of inserting data manually whenever you restart your application?


How amazing it's would be adding some dummy data to test the Rest API at the run time of the application?


What if I say yes, it's possible in the Spring boot?


Well, you can create a data.sql inside the src/main/resource folder and write the SQL database queries likes below.


 insert into Books values(101, 'Deathly Hallows', 'J. K. Rowling');
 insert into Books values(102, 'Half-Blood Prince', 'J. K. Rowling');
 insert into Books values(103, 'Order of the Phoenix', 'J. K. Rowling');
 insert into Books values(104, 'Goblet of Fire ', 'J. K. Rowling');

How to access H2 Database

As you know, we have used an in-memory h2 database. But wait, if we have used an in-memory database, then how we will reach it? Let's think.


Of course, we will access the in-memory h2 database using the default endpoint, which the Spring boot framework given. To access the in-memory h2 database, just past the following endpoint in your favorite browser URL.


http://localhost:8080/h2-console(code-box)

You can replace localhost with your IP address. Once you hit this URL, you will get the following screen.


H2 Database login page

The best practice is before connecting to the database is first to Test Connection. But how we can test the connection? How to know the in-memory database is connected to our Rest API successful?


To test the connection, Just click on the Test Connection after providing the credentials on the h2 database login page. If no error, then you will get Test successful.


Now snap the connect button of the h2 database login page, and you will redirect to the H2 Database console.


In the H2 database console, write a query to fetch all the Books table data. But wait for a second, will we get any data at the first retrieving all the Books table before adding any element?


Well, The answer is yes. Do you remember, we have created a data.sql file and wrote some insert SQL query?


At the run time of the Rest API, the Spring Boot will fire the query, which we have written in the data.sql file.


H2 Database console image, Here we are firing the SQL query to fetch all the records from the Books table

BooksRepository

Create an interface with the name BooksRepository inside the src/main/java folder and extends the JpaRepository interface as well.


The BooksRepository interface will be our DAO layer in our example.


 package in.learnjavaskills.springdataJPAtutorila.dao;

 import org.springframework.data.jpa.repository.JpaRepository;
 import org.springframework.stereotype.Repository;
            
 import in.learnjavaskills.springdataJPAtutorila.dto.Books;
            
 @Repository
 public interface BooksRepository extends JpaRepository {}

The JpaRepository is a repository interface provided by the Spring Data JPA.


The @Repository annotation is, used to indicate that this interface is a repository.



Service layer

Let's create a service layer to write business logic.


It's the best practice to distribute our business logic code.


The advantage of having a separate business logic layer is if, in the future, we need to update or alter some change the code, At this, we can easily update code from the service layer without touching the control layer.


First, we will be building an interface for service, Create an interface with BooksService named.


And for performing CRUD operation, we will be adding the following methods.


 package in.learnjavaskills.springdataJPAtutorila.service;
 import java.util.List;

 import org.springframework.stereotype.Service;

 import in.learnjavaskills.springdataJPAtutorila.dto.Books;

 @Service
 public interface BooksService 
 {
     public List getAllBooks();
     public Books addBook(Books Book);
     public void deleteBookByID(Long id);
     public Books updateBookById(Long id, Books book);
 }

We will now create an implementation BooksServiceImpl class for the BooksService interface.


 package in.learnjavaskills.springdataJPAtutorila.service;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;

 import in.learnjavaskills.springdataJPAtutorila.dao.BooksRepository;
 import in.learnjavaskills.springdataJPAtutorila.dto.Books;

 @Service
 public class BooksServiceImpl implements BooksService 
 {
     @Autowired
     private BooksRepository bookRepository;
    
     @Override
     public List getAllBooks()
     {
         return bookRepository.findAll();
     }

     @Override
     public Books addBook(Books book) 
     {
         return bookRepository.save(book);
     }

     @Override
     public void deleteBookByID(Long id)
     {
         bookRepository.deleteById(id);
     }

     @Override
     public Books updateBookById(Long id, Books book)
     {
         book.setId(id);
         return bookRepository.save(book);
     }
 } 

The @Service annotation indicates that the class is service.


Controller layer

Enough for the service layer, Now Last and the final layer is the control layer. Let's create a Java BooksController class to handle the request from the server.


 package in.learnjavaskills.springdataJPAtutorila.controller;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.DeleteMapping;
 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.PutMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RestController;

 import in.learnjavaskills.springdataJPAtutorila.dto.Books;
 import in.learnjavaskills.springdataJPAtutorila.service.BooksService;

 @RestController
 public class BooksController 
 {
     @Autowired
     private BooksService bookService;
    
     @GetMapping(path = "getAllBooks")
     private List getAllBooks()
     {
         return bookService.getAllBooks();
     }
    
     @DeleteMapping(path = "deleteBookById/{id}")
     private void deleteBookById(@PathVariable Long id)
     {
         bookService.deleteBookByID(id);
     }
    
     @PostMapping(path = "addBook")
     private Books addBook(@RequestBody Books book)
     {
         return bookService.addBook(book);
     }
    
     @PutMapping(path = "updateBookById/{id}")
     private Books updateBookById(@PathVariable Long id, @RequestBody Books book)
     {
         return bookService.updateBookById(id, book);
     }
 }

The @RestController annotation used to indicate the class is a controller.


There are two types of controller annotations in the spring boot framework, such as @Controller and @RestController.


For this example, we have used @RestController annotation because It's the best practice to use @RestController annotation when you are building a rest API.


You can use @Controller annotation in your MVC architecture project.


The @Autowired annotation in the spring boot framework is, used for initializing the Object.


The Spring Boot Framework creates beans when you use @Component, @Service, @Repository annotations.


The @GetMapping, @PostMapping, @DeleteMapping, and @PutMapping annotation, are used to perform CRUD operations. Use all annotations at the correct request. Don't use @GetMapping for the delete request and vice versa.


How to test this application?


The following are the URL for accessing our Rest API.


Description URL
Fetching all books
http://localhost:8080/getAllBooks(code-box)
Adding one book at a time
http://localhost:8080/addBook(code-box)
Deleting book by id
http://localhost:8080/deleteBookById/{book id}(code-box)
Update book by id
localhost:8080/updateBookById/102(code-box)

Let's test the application using the postman API

The postman is a desktop application, designed and developed for the backend developer to test there Rest API. If you have not yet installed a postman on your computer, then what you are waiting for? download the Postman.


It looks you have installed postman in your machine. Now launch postman and let's try to fetch all the Books table records from H2 database.


Get request from postman desktop application

Learn More How to use postman to test Rest API?


Let's add one book using postman desktop application software.


Adding data from postman

Response from the server for adding a book.


Adding data using postman response

Now Let's confirm, is data added in the in-memory H2 database?


H2 Database console, verifying data is added in h2 database

It seems, Now the in-memory H2 database is getting updated. cheers


Enough for adding, Now let's update this book which we have added recently i.e. id=1.


Updating the book using postman API desktop application

In the above image, we are updating the title book for the id=1. And here is the response from the server.


Response for updating Book using postman desktop application

Let's cross verify, the in-memory H2 database for the update request.


Confirming update request in H2 database

Once again cheer, everything is working as expected.


Finally, Let's delete the book using the book id


Deleting record using the postman desktop application

Let's confirm in the in-memory H2 databse, does record is updated or not.


Confirming the delete requestion from postman desktop application

This way you can test your Rest API using the Postman.


Conclusion


Isn't it cakewalk learning and building your first spring Data JPA using the Spring boot?. In this article, we have discussed what is JPA, What is Spring Data JPA, and how to use it in the spring boot?


You can clone this example from the GitHub.


If you find this article is valuable, then make sure you subscribe to this blog. So that in the future, if I publish a new blog, you don't miss it.


hanks for reading and Keep Learning.

(getButton) #text=(Next: Configure MySQL database in spring Data JPA) #icon=(link) #color=(#2339bd)

Post a Comment

1 Comments
  1. JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application. It is currently used as the replacement for complex entity beans. The implementation of JPA specification are provided by many vendors such as: Hibernate. best courses to learn spring data jpa

    ReplyDelete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top