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

最后修改: 2022年 5月 17日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

让我们先简单回顾一下JPA规范和它们的用法。

2. JPA Specifications

2.JPA规格

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:

在本文的代码示例中,我们将使用AuthorBook类。

@Entity
public class Author {

    @Id
    @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) ->
          criteriaBuilder.like(root.<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:

最后,我们需要AuthorRepository来扩展JpaSpecificationExecutor

@Repository
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:

因此,我们现在可以把这两个规范连在一起,用它们创建查询。

@Test
public void whenFindByLastNameAndFirstNameLike_thenOneAuthorIsReturned() {
    
    Specification<Author> specification = hasLastName("Martin")
      .and(hasFirstNameLike("Robert"));

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

    assertThat(authors).hasSize(1);
}

3. Joining Tables With JPA Specifications

3.用JPA规范连接表

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

我们可以从我们的数据模型中观察到,Author实体与Book实体共享一个一对多的关系。

@Entity
public class Book {

    @Id
    @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:

现在让我们把这个新的规范与之前创建的规范结合起来。

@Test
public void whenSearchingByBookTitleAndAuthorName_thenOneAuthorIsReturned() {

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

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

    assertThat(authors).hasSize(1);
}

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

最后,让我们看一下生成的SQL,看看JOIN子句。

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

4. Conclusion

4.总结

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

在这篇文章中,我们学习了如何使用JPA规范来查询一个基于其相关实体之一的表。

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.

像往常一样,源代码可以在GitHub上获得