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);
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?