【问题标题】:Spring data jpa count by querySpring data jpa count by query
【发布时间】:2017-07-20 18:39:45
【问题描述】:

我的用户包含一组课程,你只需要获取学生注册的课程数。我不想加载学生,因为这将加载整个学生图形对象以及其他属性,如地址等。有没有办法使用 spring data jpa 来获取计数。

【问题讨论】:

    标签: hibernate jpa spring-data-jpa


    【解决方案1】:

    您可以在 StudentRepository 中添加如下方法(假设您的实体 Student pk 作为 id 并将属性名称设置为课程)

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

    或者,您也可以在 CourseRepository 中添加如下计数方法(假设课程与学生的多对一关系,pk 和属性名称为 id 和学生)

    long countByStudentId(long id);
    

    【讨论】:

    • 这样的查询怎么样SELECT a.tagid, a.tagName, size(*) FROM articletaglist a GROUP BY a.tagName
    【解决方案2】:

    由于您有 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 应用于命名本机查询,例如(将 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") 
    

    【讨论】:

    • 我尝试了解决方案 1,我得到原因:org.hibernate.hql.internal.ast.QuerySyntaxException: [表名] 未映射。注意bean中没有放注解
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2014-08-31
    • 2017-08-21
    相关资源
    最近更新 更多