简体   繁体   English

Spring 数据 jpa 按查询计数

[英]Spring data jpa count by query

I have users containing set of courses and U need to just get the count of courses a student is enrolled into.我有包含课程集的用户,而您只需要获取学生注册的课程数量。 I do not want ti load the student since this will load the entire student graph object with othe attributed like address etc etc. Is there a way using spring data jpa to get just the count.我不想加载学生,因为这将加载整个学生图形对象,并带有其他属性,如地址等。有没有办法使用 spring 数据 jpa 来获取计数。

You can add a method such as below in your StudentRepository (assuming your entity Student pk as id and set property name as courses)您可以在 StudentRepository 中添加如下所示的方法(假设您的实体 Student pk 为 id 并将属性名称设置为课程)

@Query("select size(s.courses) from Student s where s.id=:id")
long countCoursesByStudentId(@Param("id") long id);

Alternatively you can also add a count method as below in your CourseRepository (Assuming ManyToOne Relation of Course to Student, pk and name of property as id and student)或者,您也可以在 CourseRepository 中添加如下计数方法(假设课程与学生的多对一关系,pk 和属性名称为 id 和学生)

long countByStudentId(long id);

as you have N to Many relations, you can use size() function for courses from the user.由于您有 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 ();

Also, you can use a native query to select only that you need.此外,您可以使用本机查询来仅选择您需要的。 Native query result is array of objects, but you can apply @SqlResultSetMapping for named native query like (add SqlResultSetMapping into entity , or in xml config file):本机查询结果是对象数组,但您可以将 @SqlResultSetMapping 应用于命名本机查询,例如(将 SqlResultSetMapping 添加到 entity ,或在 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") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM