jpa 数组字段_使用数组的JPA查找

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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值