Spring Data JPA中如何计算相关实体数量?

6

我有一些包含课程集合的用户,我只需要获取所注册课程的数量。但我不想加载整个学生对象,因为它会加载整个学生图形对象以及其他属性(如地址等等)。是否有一种方法可以使用Spring Data JPA仅获取计数?

2个回答

11
您可以在您的StudentRepository中添加以下方法(假设您的实体Student的主键为id,且courses属性为集合类型):
@Query("select size(s.courses) from Student s where s.id=:id")
long countCoursesByStudentId(@Param("id") long id);

或者您也可以按照以下方式在CourseRepository中添加一个计数方法(假设Course与Student之间存在ManyToOne关系,属性的主键和名称分别为id和student)

long countByStudentId(long id);

像这样的查询怎么样:SELECT a.tagid,a.tagName,size(*) FROM articletaglist a GROUP BY a.tagName - Abhishek Ekaanth

1

由于您拥有N对多关系,因此您可以使用size()函数来获取用户的课程数量。

public class UserIdCountCourses {
    private Long userId;
    private Integer countCourses;

    public UserIdCountCourses(Long userId, Integer countCources) {
        this.userId = userId;
        this.countCourses = countCources;
    }

    public Long getUserId() {
        return userId;
    }

    public Integer getCountCourses() {
        return countCourses;
    }
}

@Query("select new package.....UserIdCountCourses(u.id , size(u.cources)) 
                                           from User u group by u.id")
List<UserIdCountCourses> findUserIdAndCountEnrolledCourses ();

此外,您可以使用本地查询来选择所需内容。本地查询结果是对象数组,但您可以为命名本地查询应用@SqlResultSetMapping(将其添加到实体中或在xml配置文件中):
@SqlResultSetMapping(
    name="UserIdCountCoursesMapping",
    classes={
        @ConstructorResult(
            targetClass=UserIdCountCourses.class,
            columns={
                @ColumnResult(name="user_id"),
                @ColumnResult(name="count_courses")
            }
        )
    }
)
--just query example
@NamedNativeQuery(name="getUserIdCountCourses", query="SELECT user_id,count (1) FROM user LEFT JOIN cources cu ON user_id=cu.user_id",resultSetMapping="UserIdCountCoursesMapping") 

我尝试了解决方案1,但是出现了 Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: [table name] is not mapped 错误。请注意,在 bean 中没有放置任何注释。 - user666

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接