Spring Data JPA : How to write subquery having IN operator

11,600

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);
Share:
11,600
Soumyabrata Purakayastha
Author by

Soumyabrata Purakayastha

Updated on July 15, 2022

Comments

  • Soumyabrata Purakayastha
    Soumyabrata Purakayastha almost 2 years

    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.

  • randyr
    randyr almost 8 years
    Also take a look at this
  • rilaby
    rilaby almost 4 years
    As long as your examples use JPQL nativeQuery = true should be omitted.