Spring JPA数据获取联接重复值

时间:2019-07-16 09:13:49

标签: spring-boot jpa spring-data-jpa

我需要通过课程ID获取一些课程。我随课程参加课程,并且符合我的期望。但是当我离开联接获取以防止查询N + 1时。我的结果是重复的。

以下是代码重复的结果:

 @Query(value = "SELECT m " +
    "FROM YtClass m " +
    " INNER JOIN FETCH m.course c " +
    " LEFT JOIN FETCH m.classStudents cs " +
    " LEFT JOIN FETCH cs.student " +
    " LEFT JOIN FETCH m.classSubjects css " +
    " LEFT JOIN FETCH css.subject  " +
    "WHERE c.id = :courseId AND m.status = :status",
    countQuery = "SELECT count(m.id) FROM YtClass m WHERE m.course.id = :courseId AND m.status = :status")
  Page<YtClass> findAllByCourseId(
@Param("courseId") String courseId, @Param("status") String status, Pageable pageable);

这是正确的结果:(查询N + 1个问题)

 @Query(value = "SELECT m " +
    "FROM YtClass m " +
    " INNER JOIN FETCH m.course c " +
    "WHERE c.id = :courseId AND m.status = :status",
    countQuery = "SELECT count(m.id) FROM YtClass m WHERE m.course.id = :courseId AND m.status = :status")
  Page<YtClass> findAllByCourseId(
@Param("courseId") String courseId, @Param("status") String status, Pageable pageable);

0 个答案:

没有答案