Many To Many Query in JPA springboot

 Many To Many Query in JPA springboot

To perform a many-to-many query using JPA in Spring Boot, you will typically need to use the @ManyToMany annotation to map the relationship between the entities. Here are the steps you can follow:

  1. Define the entities: Let's say you have two entities, Student and Course, with a many-to-many relationship between them. In the Student entity, you can define the relationship as follows:
@Entity
public class Student {
    @Id
    private Long id;
    private String name;

    @ManyToMany
    @JoinTable(
            name = "student_course",
            joinColumns = @JoinColumn(name = "student_id"),
            inverseJoinColumns = @JoinColumn(name = "course_id"))
    private Set<Course> courses = new HashSet<>();
}

Similarly, in the Course entity, you can define the relationship as follows:

@Entity public class Course { @Id private Long id; private String name; @ManyToMany(mappedBy = "courses") private Set<Student> students = new HashSet<>(); }

  1. Define the repository: You can define a repository interface to interact with the database. Here's an example of how you can define a repository method to retrieve all students enrolled in a given course:
@Repository public interface CourseRepository extends JpaRepository<Course, Long> { @Query("SELECT s FROM Student s JOIN s.courses c WHERE c.id = :courseId") List<Student> findStudentsByCourseId(@Param("courseId") Long courseId); }

  1. Use the repository in your code: Once you have defined the repository, you can use it in your code to perform the many-to-many query. For example:
@Service public class CourseService { @Autowired private CourseRepository courseRepository; public List<Student> getStudentsByCourseId(Long courseId) { return courseRepository.findStudentsByCourseId(courseId); } }

Comments