How can I write a JPA repository method with property expressions that check for the existence of multiple items, or properties on those items, in a list? I can lookup a single item in the list, see zip code below, but I'm trying to write a way to check for multiple zip codes, where each Person in the result set has both zip codes in their list of addresses.
@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
// Works
Set<Person> findAllByAddresses_ZipCode(String zip);
// Doesn't work - does not return expected results
Set<Person> findAllByAddresses_ZipCode_And_Addresses_ZipCode(String zip1, String zip2);
}
My current hack is to fetch two sets for 2 zip codes, then find the intersection of the two sets:
public @ResponseBody
Iterable<Person> personsWithBothZipCodes(@PathVariable("zip1") String zip1,
@PathVariable("zip2") String zip2) {
Set<Person> a = personRepository.findAllByAddresses_ZipCode(zip1);
Set<Person> b = personRepository.findAllByAddresses_ZipCode(zip2);
// Only return results that contain both zip1 and zip2.
a.retainAll(b);
return a;
}
The entity looks like this:
@Entity
public class Person
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// zipcode is a String property on an Address.
@OneToMany(targetEntity = com.data.Address.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Address> addresses = new ArrayList<Address>();
...
}
Is there a way to write this as part of the method header? Relevant docs