Search code examples
javahibernatejakarta-eejpa

JPA lookups with arrays


I have an unidirectional relationship. Here i have Employee and Andress entities. In Employee entity i have the following code:

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "HOME_ADDRESS")
private Address homeAddress;

I have an array of Adress objects and want to write a lookup that would return an array of Customer objects mapped to those adresses.

select e from Employee e where e.homeAddress.id IN '?'

I don't know what to do with the '?' part. Is the only option to loop over the address array, add id's to a string and pass it as a parameter to the query above, or is there a way to pass the array to the query and expect the same result?


Solution

  • No, you don't pass that as a String, but as a collection of IDs. And your query is invalid. It should be:

    String jpql = "select e from Employee e where e.homeAddress.id IN :addresses";
    Set<Long> addressIds = Arrays.stream(addresses)
                                 .map(Address::getId)
                                 .collect(Collectors.toSet());
    return em.createQuery(jpql, Employee.class)
             .setParameter("addresses", addressIds)
             .getResultList();
    

    This uses Java 8 to transform the array of addresses into a set of IDs, but you can of course use a goold old for loop.