【问题标题】:How to directly get Students list using Spring data jpa @Query annotation如何使用 Spring data jpa @Query 注释直接获取学生列表
【发布时间】:2018-08-13 03:43:54
【问题描述】:

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

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

方法返回值应该是List或者Page,只是不知道怎么用查询语言来定义。

我知道如何通过热切地获取该组的所有学生来获取组实体,如下所示:

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

非常感谢您的帮助。

【问题讨论】:

  • 能不能把你的实体类Group和Student放在一起

标签: spring-data-jpa


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2015-12-04
    • 2019-07-26
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多