Skip to main content

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 internally spring data JPA adds 'limit' keyword as part of query. And the limit would be define the parameters that we pass to Pageable object.
Likewise, Sort is an interface for sorting out the database query result. In this case internally spring data JPA adds 'order by' clause to result out in sorted order.
Let's see how do we implement paging and sorting with an example ,I am taking PromotionTypeJpaRepository interface -
You can see here that method is returning Page object instead of List and Pageable object is being passed as method parameters. If we want create the Pageable object manually, the service class (or other component) that wants to paginate the query results, which are returned by a Spring Data JPA repository, must create the Pageable object and pass it forward to the invoked repository method.
PageRequest is the implementation for Page interface and it takes many parameterized constructor. In this case we are passing two integer value denoting first page with page size 2. If you think on it a bit then internally while forming query spring data JPA will add limit with 2 which will help to fetch only 2 rows from database. Now if we have to sort the query results in ascending order by using the values of the name field. If we want to get the second page by using page size 10, we have to create the Pageable object by using the following code:
Here we are describing the sort direction by creating Sort object and passing Direction into it. If we want to sort the query results in ascending order, we have to append the keyword Asc to the method name of our query method. On the other hand, if we want to sort the query results in descending order, we have to append the keyword Desc to the method name of our query method.
Internally spring data JPA will add order by clause while query in database to implement sorting.

Custom Repository

One of the very important concept that I am going to discuss here is to create a custom repository. In an enterprise application it is most viable to add custom method apart from the one that spring data JPA provides.
It is shown in the above picture the best practice to create a custom repository. I will explain this by using an example-
First create a MyJpaRepositoryCustom interface with a customMethod() as follow :
Create MyJpaRepository which implements JpaRepository and have MyJpaRepositoryCustom interface implemented into it-
Now while creating the implementation for custom interface you must have name ending with 'Impl' with custom JpaRespository in this case name would be 'MyJpaRepositoryImpl' -
The above class will have implementation for all methods defined in custom interface and also have access for JpaRepository methods. At application starts up spring data JPA would look for implementation of MyJpaRepository interface with 'Impl' added into it(MyJpaRepositoryImpl). So in any of spring component or in Service class if custom interface methods are called it automatically call the implementation defined in 'Impl' class.

Auditing Support

When you are dealing with large scale enterprise data then it is very likely to know that "when the data was created ?" ,"who created the data ?" ,"when was it last modified ?". Spring data JPA also provide support for auditing by using annotation. Following annotations are used by spring data JPA for auditing-
  • @CreatedBy : It can be used if there is an User type data.
  • @CreatedDate : It is used for DateTime data type.
  • @LastModifiedBy : It is used to give information about last modified data with User type.
  • @LastModifiedDate : It is used for last modified DateTime data type.
All these annotations are used on the instance variables of an entity. Spring also provides an AuditorAware interface for auditing purpose.
You can see that Java class for configuration is being used and AuditorAware bean has been set up. To perform auditing you have to enable spring data JPA auditing by using @EnableJpaAuditing.

Locking

Locking is very critical concept when you are dealing with data access layer. Locking is set up for a table when multiple user trying to modify the concurrently access data. Spring data JPA provides @Version annotation to implement locking strategy as below .
Whenever any data is being modified by multiple user at the same time ,the persistence manager checks for the variable annotated with @Version inside an entity. Every time data is modified persistence manager update the value of variable annotated with @Version. When you set up locking the persistence manager will check the latest version of an entity and prevent the entity to modify.
There are two type of locking -
  • Optimistic locking : If version number doesn't match throw OptimisticLockException.
  • Pessimistic locking : When this type of locking is used it locks the data for long term for the transaction duration, preventing others from accessing the data until the transaction commits.
The locking can be implemented by using @Lock annotation as below :
We provide @Lock annotation on query methods in custom Jpa Repository and pass LockModeTye parameters for the type of locking.
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