JPA lookups with arrays

孤街浪徒 提交于 2019-12-12 04:24:08

问题


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?


回答1:


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.




回答2:


2 Solutions:

  1. HQL

    String hql="select e from Employee e where e.homeAddress.id IN (:addresses)";
    Query query = getSession().createQuery(hql);
    query.setParameterList("addresses", your_list_address_collection);

  2. Criteria

    Criteria criteria = session.createCriteria(Employee.class); criteria.add(Restrictions.in("addresses", your_list_address_collection));



来源:https://stackoverflow.com/questions/28208794/jpa-lookups-with-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!