0

I have Student entity. Students have list of subjects in ManyToMany relationship. Something like this:

@Entity
@Table(name = "students")
public class Student {
@ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "student_subject", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "subject_id"))
    private List<Subject> subjects ;
}

I want to get all students that contain any of the requested subjects in my repository, something like this:

List<Student> findBySubjects(List<Subject> requestedSubjects)

Is this the right way to go? If not, is it even possible to do it like this? Thanks!

2
  • Welcome to SO. Please have a look here to learn how to improve your questions (formatting, proofreading, providing code etc.): stackoverflow.com/help/how-to-ask Commented Apr 20, 2018 at 19:59
  • 1
    Will do, thanks for the info! Commented Apr 25, 2018 at 21:26

1 Answer 1

1

You can use @Query annotation.

@Query("SELECT student FROM Student student INNER JOIN student.subjects subject WHERE subject IN (:subjects)")
List<Student> findBySubjects(@Param("subjects") List<Subject> requestedSubjects)
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, it is implemented. Will inform when I test it out. Thanks!
Works like a charm! Went into depth a little bit with custom queries, have better knowledge of it now thanks to you! Mustache gracias :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.