Skip to main content

Getting Started With Spring Data JPA


Spring data JPA is the most sought framework for connecting spring application to the database.It is a very vast topic ,I will try to cover from basic to intermediate level.Our goal is to how to write our persistence layer codebase in spring application using spring data JPA. I will first covering the bit of theory part then I would be giving an example to demonstrate these concept.
Before getting deep dive into Spring data JPA ,look at below code for performing basic CRUD operation in database using JPA entity manager.
As you can see above the amount of code needed to perform crud operation in database.This is standard code that one's follow if you are going to build persistence tier using JPA.I am not going to explain the details of JPA here as my more focus is to demonstrate spring data JPA.JPA stands for Java persistence API ,it is an API for doing transaction in database.
The same operation you can perform in spring data JPA by writing minimal code.Loot at below example for performing crud operation using spring data JPA.
As you can see the amount of code that drastically reduced by spring data JPA.You must have realized that how simple it is to write persistence tier code using spring data JPA.I will explain each piece of it so hold on yourself.

What is Spring Data JPA

Now that you have got the basic of what spring data JPA can do.Let's talk about what it is and the features that it provides.Spring data JPA is simple to use while performing operation in database.Some of the great features provided by spring data JPA is -
  • Enhances standard JPA with spring
  • Simplifies you data access layer
  • Repository generator
  • Query DSL
  • Auditing and paging
I will be explaining all the above features is different module.

Prerequisite

Spring data JPA is built on top of some of existing technology as this module is solely for understanding spring data JPA but it is important if you know basic of -
  • Java persistence API
  • Basic hibernate concept
  • Object relation mapping
  • Entity relationships
  • Spring core and JDBC
Though not recommended to know everything about above topics but basic understanding would be suffice.The reason is spring data JPA uses some of these concept while writing persistence layer codebase.
To develop spring data JPA you need below tools install in your system-
  • JDK 1.8+
  • Maven 3+
  • IDE of your choice
I would consider that you have above tools install as I am not covering the installation part.

Choosing a Data Access Layer

Whenever you working for an application and wants to choose a data access layer for persistence tier, well you have variety of options to choose in.It is not really easy to decide which one to pick ,in some scenarios you may have to choose multiple data access layer for your application.A best chosen data access layer would be the hybrid of framework.Since here we are discussing about spring data JPA ,we will discuss about the best place where spring data JPA can be used.
These are some of best options that you can choose for data access layer :
  • JDBC or Spring JDBC : It is used for simple DB's native SQL needs if your data base table architecture is not very complex.
  • Spring batch : If you have massive amount of data with hight number of SQL writes like insert and update ,choosing batch related framework would be best option.
  • ORM(JPA/Hibernate or Spring data JPA : If you are dealing with data graph without excessive relationships probably ORM would be best option to support.As it has multiple mapping like one to one and many to one etc.If mapping is less and need to perform basic operation in data base table entity choosing spring data JPA would be good option.
  • No Sql or MongoDB : Used for topic and threaded relational data.
Again it all depends upon the kind of application that you are going to create and which is the best that can fit into your application.Make sure you take everything in count if your building a data access layer for your application.
Spring data JPA goal is to make working with variety of persistence storage easier if you are to use them directly.If you need easy access to data base tier like fetching data from a table and doing basic CRUD operation then spring data provides repository with ability of cross-store persistence and dynamic query generation.
Spring data has Spring data commons which has implementation for multiple data layer and spring data JPA is one of them.The others are Spring data MondoDB ,Spring data Neo4j ,Spring data redis, Spring data REST ,Spring data Cassandra and many mores.I am here to focus on only spring data JPA.

Project Overview

To learn spring data JPA in details, I am going to create a project and demonstrating you the working of spring data JPA with example.Before moving forward I would recommend you to download project from https://github.com/maverickvishnu/springboot-demo.In my previous post on spring boot I have created a promo-api project.I am going to extend same project to introduce spring data JPA as well.I will discuss all the concept on spring data JPA.Though it is not essential to learn spring boot as spring data JPA is an independent concept but if you are interested you can scan through my post once on spring boot.
I have used embedded H2 database and flyway DB to migrate data ,you can use any data base.In this module the more focus is on persistence tier. We will write JUnit to test spring data JPA code as our main focus in on model part.
To Create spring data JPA in your project first you have to include spring data JPA dependency.As we are building an application by using spring boot ,spring boot provides spring-boot-starter-data-jpa dependency for spring data JPA.Add below dependency in pom.xml-
In below picture I have defined the data model for our project-
In the project that we already downloaded has PromotionRepository configure.Go to the com.zerototech.repo package and you can see PromotionRepository interface open that up.You can see PromotionRepository is extending generic JpaRepository. Here JpaRepository is made generic by passing Promotion entity and ID. Spring data JPA provides JpaRepository with set of methods for CRUD operation.In spring data JPA for each model defined we create a repository so that we can perform set of operation on entity defined.In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface – JpaRepository. This will enable Spring Data to find this interface and automatically create an implementation for it.I will explain in details for now let's create a test class to test whether PromotionRepository is working fine.Add below lines of code-
As you can from above code that we are able to fetch data from Promotion repository.Congrats!!! you have created a first repository using spring data JPA.I will explain in details what is happening behind the scene.

Spring Data JPA Repository

You must be wondering by now that how spring data JPA is working internally, how data is being fetched from data base without writing any fetch query.Now it's time to delve into what is happening behind the scene.Before understanding spring data JPA let understand about spring repositories.What do you understand if somebody tell you about repository as name suggests it is a kind of data storage. Technically repositories whole point is to define a contract that data access layer will implement.The contract is an interface that bind to client code that need a data access.
In the above diagram you can see in a typical spring application there is a service layer and data access layer.Consider that service needs to get data from DAO.When service layer communicates with data access layer behind the scene DAO will have implementation to fulfill service request so we define DAO Interface contract.Now this interface either can be implemented using JDBC or JPA.The important point to note here the service layer is not aware of DAO implementation.It just uses the operation given by repository interface.In case of spring data JPA the DAO interface is implemented by using JPA.

Repository Architectural Overview

When we talk about repository it is nothing but a storage.In a relational database repository is nothing but a table.In a typical web application there could be many tables and they may or may not be related to each other.
In the above diagram shows how a typical spring application look like.It has multiple layer to talk to while serving a request. In a real world a database would be different server.If you are developing a web application and your application needs to communicate to data base server you need a data access layer.Now that you have decided to use JPA repository for data access layer so this JPA repository will have an entity which will be mapped to database table.This how simple ORM framework works where you are mapping an object with a table.In case of spring data repository an entity is mapped one to one with JPA repository.By keeping the JPA repository focus on a single entity keeps the DAO pattern limited to that specific data and data structure.In spring service will talk to couples of JPA repository to bundle up different data from multiple entity.And finally the controller will be conversing to service to respond to a request.
Below are some of important points to remember about JPA repository -
  • JPA repository is a Java interface not a class
  • Repository is mapped one to one with JPA entity
  • Focuses on DAO contract
To create a JPA repository first create a repository interface .This interface will extends JpaRepository interface. JpaRepository is a generic type and it takes entity and the primary key of an entity as shown below.
Whenever application starts up the spring data JPA will recognize JPA repository and automatically generates implementation for the DAO contract specify in the interface.

JPA Repository Feautures

The Repository interface has only CRUD operations defined, But there are others bunch of repository interface which JpaRepository interface extends that has many more methods for different functionality.
You can see in above diagram that JpaRepository is extending three different interface and all these interface is defined for providing different functionality.The spring data JPA only provides JpaRepository interface other interface have come up from core spring data.
  • Query DSL : This feature is given by Repository interface.
  • CRUD Operations : This feature is given by CrudRepository interface.It provides bunch of helper methods as well -
    • count() : To counts the total number of rows present in a table.
    • exists(Long id) : To find record is available for given id.
  • Paging and Sorting : Paging and sorting functionalities are provided by PagingAndSortingRepository interface.
Since the JpaRepository interface extends all other interfaces it consists all the above functionalities.This interface also provides helper methods like flush() and deleteInBatch(Interable entities), to flush out the data and to delete data in batches.
When you are working for data access layer you should always think of bigger picture this includes setting up convenience methods or operations for custom repository that can be used across the board.If you have to create a repository which bunch of common methods you should always create a custom repository having common methods and create another repository interface which extends your custom repository.This is the best practice to create a custom repository and to save code reusability.
To explain this let me show you an example ,let's create a class names PromotionType-
Now create a JpaRepository of above model entiry-
If we happen to use the above created JpaRepository in any of service class or controller class the best practice is instead of using this repository directly it is better to create one custom class repository with required operations.
As you can see the custom class is annotated with @Repository explains this class is a repository class.Inside custom class custom JpaRepository interface has been autowired and custom methods have been defined for performing different JPA operations.
In this post we have learned the basics of JPA repository and have created Jpa repository as well.We have also learned the different features of Jpa repository and how is it working internally.I will cover the Query DSL in my next post as query DSL is a big topic in itself.
Note : Your feedback and comments would be highly appreciated ,kindly do provide your feedback. As spring data JPA is a very vast topic hence I have covered it by multiple post. In order to learn and understand spring data JPA completely you need go through each post. Below mentioned order you must follow so that you won't miss anything-

Comments

Popular posts from this blog

Spring Data JPA and @Query Annotation

As in the last post on query DSL, I have discussed about creating various custom finder methods to query in database. You also know that spring data JPA internally form JPQL to query in database. In this module I am going to cover query annotations that spring data JPA provides with some advanced features. @Query annotation In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. In the custom JPA repository we can define multiple query DSL methods to query data from database for different condition. Consider a case where condition being passed in the query are too many. Though you can form custom finder method but the method is going to be very large and cumbersome. In such type of scenario the best way is to write simple method and use @Query annotation on top of method. When the @query annotation is being used spring data JPA ignores the structure of f

Query DSL Overview

This post is the continuation of my previous post on spring data JPA. In this post I would be delving deeply into query DSL.Query DSL is an advanced feature provided by spring data JPA to query data from database. It has less code so less to maintain.By using query DSL one can check query at start up rather than at runtime. I am going to discuss key and concepts require to learn DSL and would learn through example. We will extending the same promo-api that we wrote in last post and would be writing Junit to verify query. DSL stands for a domain specific language and is a customized extension of a software programming language that addresses a specific business or domain. In case of spring data JPA this means the framework is enhancing Java to be better suited for creating and working with JPA query. The spring data JPA query DSL is simply all about finding terms and syntax to work with JPA query more efficiently. To demonstrate how query DSL works ,let us take an example to explain

Spring Data JPA Paging, Sorting, Custom Repository, Auditing and Locking

In this module we will talk about some of advance features that spring data JPA support for developing an enterprise application. They are paging and sorting ,auditing, locking and custom repository. Paging and Sorting As a web application developer if you have to display thousands of records on the UI it is not a good practice to just query database and display it to UI. Spring data JPA provides paging and sorting mechanism to handle such type of scenario. These are most sought problem if you are dealing with a big enterprise application, keeping this into mind spring data JPA has provided in built support for paging and sorting. You can see above that spring data JPA has PagingAndSortingRepository interface and it has findAll method. Sort and Pageable object are getting passed as part of findAll() method parameters. What do you think Pageable does behind the scene. Basically Pageable is an interface and when spring data JPA fetch value from database it limits the result. So inte