Joining Tables With Spring Data JPA Specifications – 用Spring Data JPA规范连接表

最后修改: 2022年 5月 17日

1. Overview


In this short tutorial, we’ll discuss an advanced feature of Spring Data JPA Specifications that allows us to join tables when creating a query.

在这个简短的教程中,我们将讨论Spring Data JPA规范的一个高级功能,它允许我们在创建查询时连接表。

Let’s start with a brief recap of JPA Specifications and their usage.


2. JPA Specifications


Spring Data JPA introduced the Specification interface to allow us to create dynamic queries with reusable components.

Spring Data JPA引入了Specification 接口,允许我们使用可重用的组件创建动态查询。

For the code examples in this article, we’ll use the Author and Book classes:


public class Author {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String firstName;

    private String lastName;

    @OneToMany(cascade = CascadeType.ALL)
    private List<Book> books;

    // getters and setters

In order to create a dynamic query for the Author entity, we can use implementations of the Specification interface:


public class AuthorSpecifications {

    public static Specification<Author> hasFirstNameLike(String name) {
        return (root, query, criteriaBuilder) ->
<String>get("firstName"), "%" + name + "%");

    public static Specification<Author> hasLastName(String name) {
        return (root, query, cb) ->
          cb.equal(root.<String>get("lastName"), name);

Finally, we’ll need AuthorRepository to extend JpaSpecificationExecutor:


public interface AuthorsRepository extends JpaRepository<Author, Long>, JpaSpecificationExecutor<Author> {

As a result, we can now chain together the two specifications and create queries with them:


public void whenFindByLastNameAndFirstNameLike_thenOneAuthorIsReturned() {
    Specification<Author> specification = hasLastName("Martin")

    List<Author> authors = repository.findAll(specification);


3. Joining Tables With JPA Specifications


We can observe from our data model that the Author entity shares a one-to-many relationship with the Book entity:


public class Book {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    // getters and setters

The Criteria Query API allows us to join the two tables when creating the Specification. As a result, we’ll be able to include the fields from the Book entity inside our queries:

标准查询 API允许我们在创建Specification时连接这两个表。因此,我们将能够在我们的查询中包含来自Book实体的字段。

public static Specification<Author> hasBookWithTitle(String bookTitle) {
    return (root, query, criteriaBuilder) -> {
        Join<Book, Author> authorsBook = root.join("books");
        return criteriaBuilder.equal(authorsBook.get("title"), bookTitle);

Now let’s combine this new Specification with the ones created previously:


public void whenSearchingByBookTitleAndAuthorName_thenOneAuthorIsReturned() {

    Specification<Author> specification = hasLastName("Martin")
      .and(hasBookWithTitle("Clean Code"));

    List<Author> authors = repository.findAll(specification);


Finally, let’s take a look at the generated SQL and see the JOIN clause:


select as id1_1_, 
  author0_.first_name as first_na2_1_, 
  author0_.last_name as last_nam3_1_ 
  author author0_ 
  inner join author_books books1_ on = books1_.author_id 
  inner join book book2_ on books1_.books_id = 
  author0_.last_name = ? 
  and book2_.title = ?

4. Conclusion


In this article, we learned how to use JPA Specifications to query a table based on one of its associated entities.


Spring Data JPA’s Specifications lead to a fluent, dynamic, and reusable way of creating queries.

Spring Data JPA的规范带来了一种流畅、动态和可重用的创建查询的方式。

As usual, the source code is available over on GitHub.