Filip Bob
Filip Bob

Reputation: 13

Get data using spring repository when relation one to many

So I have two classes Movie and Genres in relation one-to-many. What I want to do is to get List of Movies filtred by Genres name using Spring repositorys. I want to be able to do something like:

List<Movie> movies = movieRepository.getMoviesByGenres(Arrays.asList("Drama", "Comedy"))

I was tring to do it like belowe, but this not wokrs, is there any option to do this using spring repository?

@Entity
public class Movie {

  @Id
  @Column(name = "movie_id")
  private long id;
  private String title;
  @OneToMany(mappedBy = "movie")
  private Set<Genres> genres;
  ...
} 

-

@Entity
public class Genres {

  @Id
  private long id;
  @ManyToOne
  @JoinColumn(name = "movie_id", nullable = false)
  private Movie movie;
  private String name;
  ...
}

-

public interface MovieRepository extends JpaRepository<Movie, Long>{

  List<Movie> getMoviesByGenres(String name);
}

Upvotes: 1

Views: 105

Answers (1)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

You need to create a method like below:

public interface MovieRepository extends JpaRepository<Movie, Long>{

  List<Movie> getMoviesByGenresNameIn(List<String> names);
}

And if you want to fetch geners relation with one query you need to decorate the method with EntityGraph like below:

@EntityGraph(attributePaths={"geners"})
List<Movie> getMoviesByGenresNameIn(List<String> names);

Upvotes: 1

Related Questions