Reputation: 14363
I have a simple One to Many relationship in my DB. Here are the corresponding Classes:
class Department
{
int deptId;
int count; //This corresponds to the total number of Employees in a department
List<Employee> employees; //An employee belongs to only one department
}
class Employee
{
int employeeId;
Department dept;
}
In order to keep the count
updated, I am setting the count
on each CUD
operation. Is there an automatic way to update the count
on each Add/Delete of an employee to the Department? (An annotation/restriction or something?)
Upvotes: 0
Views: 223
Reputation: 5303
As far as I know there is no automatic way in Hibernate.
Anyway, generally this risks to produce wrong results. What will happen if one user adds an employee and at the same time a second user removes an other employee? (This case still can be handled in Hibernate.) Or what happens if the dba adds some employees by an insert statement or loads data from a backup?
In the view of the database model this is superfluous information and should be omitted. Instead a SELECT COUNT(*) FROM employee WHERE dept =:deptId
should be used.
The only reason for the count column is if you need the count very often and you have performance problems with a select(*). For this special case there is no Hibernate automatism.
Edit:
I've just seen Overmeulens answer now. That also is working. If you only need the count, then SELECT COUNT(*)
(also can be done in HQL) is faster, if you need the employee records anyway then Overmeulens solution has better performance.
Upvotes: 0
Reputation: 1158
Why do you keep a global variable with the employees count ? Adding a method that returns the size of the employees list is safer and much more elegant.
public class Department {
private int deptId;
private List<Employee> employees;
public int getCount() {
if (employees == null) {
return 0;
}
return employees.size();
}
}
Upvotes: 1