如何在 Spring Data JPA 中编写以下子查询?
select o from Owner o where o.ownerId IN (Select c.ownerId from Cars c)
这里
Owner
是一个实体类,Cars
是另一个实体类,我有两个存储库:OwnerRepository
和CarRepository
,都扩展了JPARepository
。
如何编写带有
IN
运算符的子查询?
您始终可以将查询用作自定义查询:
@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);