Spring Data JPA:如何编写具有 IN 运算符的子查询

问题描述 投票:0回答:1

如何在 Spring Data JPA 中编写以下子查询?

select o from Owner o where o.ownerId IN (Select c.ownerId from Cars c)

这里

Owner
是一个实体类,
Cars
是另一个实体类,我有两个存储库:
OwnerRepository
CarRepository
,都扩展了
JPARepository

如何编写带有

IN
运算符的子查询?

java spring jpa spring-data spring-data-jpa
1个回答
7
投票

您始终可以将查询用作自定义查询:

@Query(value = "select o from Owner o where o.ownerId IN (Select c.ownerId from Cars c")
Owner getOwner();

如果需要将变量传递给查询,请使用

@Param
标签,如下所示:

@Query(value = "SELECT * FROM Owner o WHERE o.ownerId = :id")
Owner getOwnerWithId(@Param("id") Long id);
© www.soinside.com 2019 - 2024. All rights reserved.