Spring Data JPA: Query Derivation Explained!
Understanding Spring Data JPA with query derivation
Introduction
Spring Data JPA is a layer built on top of JPA that provides features out of the box to ease data access from the database.
The repository interface in Spring Data JPA allows us to define the data access from the database.
Spring Data JPA allows us two ways to query data from the database. defining query with query derivation and defining manual query.
In this article, we will learn about query derivation.
Query Derivation
Query derivation is a very powerful feature that allows us to just name the method in a certain way and Spring Data JPA does the job to generate Query for it.
For example, if we have PermissionRepository that extends from JpaRepository in order to get the permission entity from the type we can just define the method findByType, and whenever we access this method Spring Data JPA will generate a query for it.
public interface PermissionRepository extends JpaRepository<Permission, Integer> {
Permission findByType(String type);
}
Generated query
Query creation is the combination of subject and predicate. The subject generally starts with keywords such as find..by, count..by, read..by, etc.
List of keywords: Subject Keyword, Predicate Keywords
Use Case
Table / Entity
FindByUsername
We can add a property such as a username with FindBy
CountByUsername/CountByPermission
Similarly, we can use a username with CountBy.
CountByPermissionAndCreatedOnGreaterThan
We can define methods with predicates keywords such as AND, GREATER_THAN.
Find more info in the docs.
Conclusion
Query derivation is a very powerful feature that provides an abstraction to query databases without writing a query.
But before going too far with this we should know writing complex queries with query derivation will be challenging, in such cases writing manual queries is better.