Search code examples
springhibernatejpaspring-data-jpaspring-data

Filtering by a combination of parent and child fields in a unidirectional JPA relation


I have 2 entities in a unidirectional one-to-many relationship, but I want to query all child entities based on their own and their parent's details. Say for example I have Author (parent) and a list of Books (child) and I want to search for Books based on their title and the name of the Author. To make it simple, let's just say there's one-to-many author to books.

At the minute, I'm able to query books using author's name using a query a like this:

select a.books from Author a where name = :name

Just to reiterate, the relationship is unidirectional so there's no reference from Book to Author. How do I modify the query above to also filter by the book title?


Solution

  • Should just be “select b from Author a join a.books b where a.name = :name and b.title = :title”