使用数组的JPA查找 [英] JPA lookups with arrays

查看:1427
本文介绍了使用数组的JPA查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  @OneToOne(cascade = CascadeType.ALL)
@JoinColumn =HOME_ADDRESS)
私人地址homeAddress;

我有一个Adress对象数组,并且想要编写一个将返回一个Customer对象数组的查找映射到这些地址。

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

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

解决方案

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

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

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

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?

解决方案

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.

这篇关于使用数组的JPA查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆