简体   繁体   English

HQL:在查询中有条件地计数子集合

[英]HQL: Counting a child collection conditionally within a query

I'm fairly inexperienced when it comes to HQL, so I was wondering if anyone can help me out on this. 我对HQL缺乏经验,所以我想知道是否有人可以帮助我。 I have a relationship where Student has a OneToMany relationship with StudentCollege. 我有一个学生与StudentCollege有OneToMany关系的关系。 I'm trying to write a query that finds each student who has made an application, and how many applications they've submitted. 我正在尝试编写一个查询,以查找每位提出申请的学生以及他们提交了多少申请。 I have the following query written, but I am unsure if it's even close to what I should be doing. 我写了以下查询,但是不确定它是否接近我应该做的事情。

select distinct new ReportVO (stu.id, stu.first_name, stu.last_name, stu.year, stu.school.school_name, sum(case when si.applied = 1 then 1 else 0 end) as numApplications) " +
                    "from StudentCollege as si join si.student as stu where stu.year <= 12 and stu.user.id = :userId and si.applied = 1 order by stu.last_name

When it runs the following exception is thrown: 当它运行时,将引发以下异常:

org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [package.location.ReportVO] [select distinct new ReportVO (stu.id, stu.first_name, stu.last_name, stu.year, stu.school.school_name, sum(case when si.applied = 1 then 1 else 0 end) as numApplications) from package.location.StudentCollege as si join si.student as stu where stu.year <= 12 and stu.user.id = :userId and si.applied = 1 order by stu.last_name]

However I have a constructor for the VO object that takes in that same number of arguments, so I'm thinking the type returned from the sum is incorrect. 但是,我有一个VO对象的构造函数,该构造函数接受相同数量的参数,因此我认为从总和返回的类型不正确。 I've also tried replacing numApplications with Integer and Count , but the same exception is thrown. 我也尝试用IntegerCount替换numApplications ,但是抛出了同样的异常。

public ReportVO(int id, String firstName, String lastName, int year, String school, Integer numApplications)

Any help is appreciated! 任何帮助表示赞赏!

I believe you are a missing a "group by" clause after the where clause. 我相信您在where子句之后缺少“ group by”子句。

select distinct new ReportVO (stu.id, stu.first_name, stu.last_name, stu.year, stu.school.school_name, sum(case when si.applied = 1 then 1 else 0 end) as numApplications) " +
                    "from StudentCollege as si join si.student as stu where stu.year <= 12 and stu.user.id = :userId and si.applied = 1 group by stu.id, stu.first_name, stu.last_name, stu.year, stu.school.school_name order by stu.last_name

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

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