Maifee Ul Asad
Maifee Ul Asad

Reputation: 4607

spring jpa join and query repository

I have User class like this:

{
     ...
     Long userID;
     ...     
     List<UserMovieRole> userMovieRoles=...
}

A Movie class like this:

{
    ...
    Long movieID; 
    ...     
    List<UserMovieRole> userMovieRoles=...
}

I have another class UserMovieRole like this:

{
    Long userMovieRoleID;
    Role role;
    ...
    User user;
    ...
    Movie movie;
}

Now I want to query on UserMovieRole and select where userID and movieID is given.

In sql I can simply write, I can simply write a join and where sql to select.

But in spring boot jpa query, it seems I can't do that, how can I do that?

Here is what I have tried:

I dont't know if any of these are correct, what is the actual way of doing it ?

Upvotes: 0

Views: 80

Answers (1)

dxjuv
dxjuv

Reputation: 909

Write a query as you would in SQL in the @Query and then add another property of the annotation as nativeQuery = true and it will run the query as you would in sql.

Pass the parameters in query by adding a : in front of them. Also, don't forget to add @Param in your auguments.

Something like this:

    @Query(value = "select umr from UserMovieRole umr join user u on u.id = umr.userId  where u.userId (#got it by joining tables.) = :userId  and umr.movieID=:movieId", nativeQuery = true)
    returnType yourMethod(@Param("userId") userId, @Param("movieId") movieId);

Upvotes: 1

Related Questions