HQL:使用聚合函数进行简单选择时出现问题
我有非常简单的数据模型,如下所示:
create table Company (
id int primary key,
name varchar(50),
street varchar(50)
)
create table Person (
id int primary key,
name varchar(50),
surname varchar(50),
id_company int foreign key references Company
)
相应的java类如下:
class Company {
int id;
String name, street;
List<Person> employees;
// getters, setters, ctor
}
class Person {
int id;
String name, surname;
Company employer;
// getters, setters, ctor
}
现在,我想选择拥有大多数员工的公司HQL。我不知道如何,这是我的垃圾伪尝试,不起作用:
from Company c having max(c.employees);
I have very simple data model like this:
create table Company (
id int primary key,
name varchar(50),
street varchar(50)
)
create table Person (
id int primary key,
name varchar(50),
surname varchar(50),
id_company int foreign key references Company
)
corresponding java classes like this:
class Company {
int id;
String name, street;
List<Person> employees;
// getters, setters, ctor
}
class Person {
int id;
String name, surname;
Company employer;
// getters, setters, ctor
}
Now, I 'd like to select Company with most employees with HQL. I don't know how, here's my rubbish pseudo attempt that doesn't work:
from Company c having max(c.employees);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:这对我有用 - 获取公司 ID 和员工数量
获取公司对象:
如果您还没有 Eclipse 的 hibernate 插件,请安装它,这非常适合,因为它还显示生成的 sql,以便您可以优化您的hql,请参阅 http://www.hibernate.org/subprojects/tools.html。
想到一件事,如果 CompA 和 CompB 两家公司的员工人数最多,比如 50 人,即所有其他公司的员工人数都少于 50 人,会发生什么情况,你关心你得到的是哪家公司的 id 吗?您对数字 50 还是公司 ID 更感兴趣?
EDIT: this worked for me - to get company id and employee count
To get the company object:
If you don't have the hibernate plugin for eclipse yet install it it's great for this as it also displays the generated sql so you can optimize your hql, see http://www.hibernate.org/subprojects/tools.html.
Just thought of something, what happens if two companies CompA and CompB both have the highest number of employees, say 50, i.e. all other companies have less than 50, do you care which company id you get back? Are you more interested in the number 50 or the company id?
事实上,这并不是一件小事。我想不出一种方法可以通过单个查询来完成您想要的操作,但是您可以使用如下所示的两个查询来完成此操作:
上面的代码假设只有一家公司拥有最多的员工。当然,多家公司可能拥有相同数量的员工,而且恰好是最大数量。
It's not trivial, actually. I can't think of a way to do what you want with a single query, but you can do it with two queries using something like this:
The above code assumes that there is only one Company that has the most employees. It is possible of course for multiple companies to have the same number of employees which also happen to be the maximum.
尝试:
在代码中,您仅检索第一个元素。
Try:
In code you retrieve only the first element.
查看 Hibernate 有关 HQL 的章节,特别是聚合函数部分:
select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
来自猫猫
Check out the Hibernate chapter on HQL, specifically the aggregate function section:
select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
from Cat cat