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.

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

Further reading:

JPA Join Types

Explore different join types supported by JPA.

Use Criteria Queries in a Spring Data Application

A quick tutorial to using JPA Criteria Queries using Spring Data JPA.

Spring Data JPA and Named Entity Graphs

Learn how to better control the entities you want to fetch using Spring JPA.

2. JPA Specifications

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

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

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

@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 whenSearchingByLastNameAndFirstNameLike_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

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

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

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:

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

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.

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

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.