如何使用Spring数据jpa @Query注释直接获取学生列表

问题描述 投票:1回答:1

我有两个实体:Group和Student是ManyToMany关系,Group是所有者。

现在定义一个从JpaRepository扩展的GroupRepository,并希望使用@Query注释声明一个方法,直接获取给定GroupId的Student列表。怎么样?

方法返回值应该是List或Page,不知道如何使用查询语言定义。

我知道如何让一个Group实体急切地获取该组的所有学生,如下所示:

@Query("select group from Group group left join fetch group.students where group.id=:id")
Group findOneWithEagerRelationships(@Param("id") Long id);

非常感谢任何帮助。

spring-data-jpa
1个回答
1
投票

如果您有这样的模型:

@Entity
class Group {

   @Id Ling id;

   @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
   private List<Student> students;

   //...
}

@Entity
class Student {

   @Id Long id;

   @ManyToMany(mappedBy = "groups")
   private List<Group> groups;

   //...
}

然后,为了让所有学生通过组回购,您可以制作这样的方法:

interface GroupRepo extends JpaRepository<Group, Long> {
    @Query("select s from Group g join g.students s where g.id = ?1")
    Page<Student> getAllStudentsByGroupId(Long groupId, Pageable pageable);
}

资料来源:12

© www.soinside.com 2019 - 2024. All rights reserved.