Spring JPA One-to-Many Query Examples with Property Expressions

Joe Evans
2 min readFeb 12, 2018

In this article, I will explain some of the ways you can build out your Spring JPA repositories.

Assume we have Person and Address entities and each Person can have multiple Addresses. You want to look up Persons by a specific zip code. How can you write the query in your Repository class to traverse the database to find the result set? There are many ways to achieve this, but I will only focus on two: an ugly way, and a beautiful way.

Let’s take the Person entity class for example. Assume a Person class has a list of Addresses of type Address:

Hibernate will automatically generate entity tables and association tables for you, so you have three tables created:

- person
- address
- person_addresses

If we had to look up zip codes the ugly way, with a native query, we could accomplish it like this:

Yuck. Given how much we get from Spring for free, there has to be a better way to achieve the same outcome.

Good news! We can get the same result set with property expressions. By defining the following method in our repository interface, we can find all people by zip code:

IntelliJ even helps by listing valid keywords:

As you type out the method name, you will get a huge list of keywords mapping to the properties on your entity.

JPA uses a resolution algorithm to traverse the properties by interpreting the method header. This works for most cases, but sometimes you may need to explicitly define traversal points. This can be accomplished by using _ in the method header.

List<Person> findByAddress_ZipCode(String zipCode);

JPA will return all Persons with at least one Address that has the given zip code.

Wait a minute — there’s a lot more to an address than a zip code. What if we want to search by street address AND zip code?

List<Person> findByAddress_ZipCode_AndAddress_StreetAddress(String zipCode, String streetAddress);

JPA will return all Persons with at least one Address that has the given zip code and street address.

For more on this topic, read the Working with Spring Data Repositories docs.

--

--