使用数组的 JPA 查找

JPA lookups with arrays

我有一个单向关系。这里我有 Employee 和 Andress 实体。在 Employee 实体中,我有以下代码:

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

我有一个 Adress 对象数组,我想编写一个查找 return 一个映射到这些地址的 Customer 对象数组。

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

我不知道如何处理“?”部分。是遍历地址数组、将 id 添加到字符串并将其作为参数传递给上面的查询的唯一选项,还是有办法将数组传递给查询并期望得到相同的结果?

不,您不将其作为字符串传递,而是作为 ID 集合传递。并且您的查询无效。应该是:

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();

这使用 Java 8 将地址数组转换为一组 ID,但您当然可以使用旧的 for 循环。

2个解:

  1. HQL

    字符串 hql="select e from Employee e where e.homeAddress.id IN (:addresses)";
    查询query = getSession().createQuery(hql);
    query.setParameterList("addresses", your_list_address_collection);

  2. 条件

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