Logo

dev-resources.site

for different kinds of informations.

Spring Data JPA: About Specification interface

Published at
4/9/2024
Categories
spring
springdata
Author
saladlam
Categories
2 categories in total
spring
open
springdata
open
Author
8 person written this
saladlam
open
Spring Data JPA: About Specification interface

org.springframework.data.jpa.domain.Specification interface

The objective of Specification interface is to let developers make reusable Predicates objects to append into a query when needed.

For example, to create a query of this entity.

@Entity
@Table(name = "Customer")
public class Customer {

    @Id
    @Column(name = "custId")
    private Integer custId;
    @Column(name = "companyName", length = 40, nullable = false)
    private String companyName;
    @Column(name = "contactName", length = 30)
    private String contactName;
    @Column(name = "contactTitle", length = 30)
    private String contactTitle;
    @Column(name = "address", length = 60)
    private String address;
    @Column(name = "city", length = 15)
    private String city;
    @Column(name = "region", length = 15)
    private String region;
    @Column(name = "postalCode", length = 10)
    private String postalCode;
    @Column(name = "country", length = 15)
    private String country;
    @Column(name = "phone", length = 24)
    private String phone;
    @Column(name = "mobile", length = 24)
    private String mobile;
    @Column(name = "email", length = 225)
    private String email;
    @Column(name = "fax", length = 24)
    private String fax;

    // ignore getter and setter
}
Enter fullscreen mode Exit fullscreen mode

In order to pass Specification criteria, please add org.springframework.data.jpa.repository.JpaSpecificationExecutor into the Repository interface.

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer> {
}
Enter fullscreen mode Exit fullscreen mode

null Specification

null Specification means no criteria.

customerRepository.findAll((root, query, criteriaBuilder) -> null);
// it is equal to customerRepository.findAll();
Enter fullscreen mode Exit fullscreen mode

To get entities when a field is equal to something

To get entities whose "city" is equal to the value of the String variable "city".

String city;
// ...
Specification<Customer> s = (root, query, criteriaBuilder) -> null;
if (Objects.nonNull(city)) {
    s = s.and((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("city"), city));
}
customerRepository.findAll(s);
Enter fullscreen mode Exit fullscreen mode

and() This is used for joining two Specification with AND clauses. The other one is or().

Add one more Specification

In addition to "city", "companyName" wants to look up also.

String city;
String companyName;
// ...
Specification<Customer> s = (root, query, criteriaBuilder) -> null;
if (Objects.nonNull(city)) {
    s = s.and((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("city"), city));
}
if (Objects.nonNull(companyName)) {
    s = s.and((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("companyName"), companyName));
}
customerRepository.findAll(s);
Enter fullscreen mode Exit fullscreen mode

Code about can work on cases from no query criteria to with "city" and "companyName" criteria.

Other unnormal usage of Specification interface

You may do following

  • to JOIN other entity
  • to define complex sort if JpaSpecificationExecutor.findAll(Specification , Sort) cannot suit your need
springdata Article's
30 articles in total
Favicon
Handling Asynchronous Execution with Transactions in Spring: A Common Pitfall and How to Solve It
Favicon
Streamlined Java Data Querying
Favicon
Jakarta Persistence API (JPA) example application: Northwind sample database
Favicon
Spring Data JPA: About Specification interface
Favicon
What is implementation class of org.springframework.data.jpa.repository.JpaRepository interface?
Favicon
Spring Data JPA demonstration
Favicon
Spring Data & MongoDB — Pagination+Sorting w/ Aggregation and Lookup
Favicon
Demystifying Spring Data and Spring Data JPA: A Question-Based Guide: Simplify Your Data Access Layer
Favicon
How to Insert Records in Batch with Spring Data
Favicon
Um olhar sobre PagingAndSortingRepository
Favicon
Spring Data JPA Interview Questions and Answers
Favicon
Quick Tip: Kotlin, Spring Data, and Optionals
Favicon
Safely Evolving Database with Liquibase, Spring Data, and Spring Boot
Favicon
How to use Spring Data DynamoDB example | Spring Boot
Favicon
How to start SpringBoot ElasticSearch using Spring Data
Favicon
Apache Solr – How to start Spring Data Solr with SpringBoot
Favicon
Spring Boot + Angular 6 example | Spring Data + REST + MongoDb CRUD example
Favicon
SpringData Reactive Cassandra Repositories | SpringBoot
Favicon
Spring Data Rest – How to create a RestAPIs with JPA Many-to-Many relational entities
Favicon
SpringData DynamoDB CRUD Example | SpringBoot
Favicon
Spring Data Rest – How to create a RestAPIs with JPA One-to-Many relational entities | SpringBoot + MySql + HAL Browser
Favicon
How to access MySQL database with Spring Data Rest application
Favicon
Kotlin Spring Boot + Angular 6 CRUD + PostgreSQL example | Spring Data JPA + REST APIs example
Favicon
Spring Data Redis Messaging – PubSub example | Spring Boot
Favicon
Spring Data Redis CRUD Operations example with Spring Boot
Favicon
Your own custom Spring Data repository
Favicon
SpringData MongoDB GridFsTemplate to save, retrieve, delete binary files (Image, Text files)
Favicon
How to use SpringData MongoRepository to interact with MongoDB
Favicon
How to start Spring Data Cassandra with SpringBoot
Favicon
Angular + Spring WebFlux + Spring Data Reactive Cassandra example

Featured ones: