3

I am a new to Spring Data JPA, wanted to know how do I write the following subquery:

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

Here Owner is one entity class and Cars is another entity class and I'll be having two repositories one as OwnerRepository and the other as CarRepository, both extending JPARepository.

Help needed in writing this sort of custom queries with IN operator.

Thanks in advance.

v.ladynev
  • 19,275
  • 8
  • 46
  • 67

1 Answers1

7

You could always just use your query as a custom query:

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

If you need to pass variables to the query, use the @Param tag, like so:

@Query(value = "SELECT * FROM Owner o WHERE o.ownerId = :id")
Owner getOwnerWithId(@Param("id") Long id);
Islam Hassan
  • 673
  • 1
  • 10
  • 21
randyr
  • 1,679
  • 1
  • 11
  • 17
  • Also take a look at [this](http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-three-custom-queries-with-query-methods/) – randyr May 22 '16 at 01:02
  • As long as your examples use JPQL `nativeQuery = true` should be omitted. – rilaby May 04 '20 at 09:55