简体   繁体   English

使用Hibernate更新表中“许多”项的计数

[英]Updating the count of 'many' items in a Table using Hibernate

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. 为了使count保持更新,我在每个CUD操作上设置count Is there an automatic way to update the count on each Add/Delete of an employee to the Department? 有没有一种自动的方法来更新员工到部门的每次添加/删除的count (An annotation/restriction or something?) (注释/限制或其他内容?)

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();
   }
}

As far as I know there is no automatic way in Hibernate. 据我所知,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? (这种情况在Hibernate中仍然可以处理。)或者,如果dba通过insert语句添加了一些员工或从备份中加载了数据,会发生什么?

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. 而是应使用SELECT COUNT(*) FROM employee WHERE dept =:deptIdSELECT COUNT(*) FROM employee WHERE dept =:deptId

The only reason for the count column is if you need the count very often and you have performance problems with a select(*). 计数列的唯一原因是,如果您非常需要计数,并且select(*)出现性能问题。 For this special case there is no Hibernate automatism. 对于这种特殊情况,没有休眠自动机。

Edit: 编辑:

I've just seen Overmeulens answer now. 我刚刚看到Overmeulens回答。 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. 如果仅需要计数,则SELECT COUNT(*) (也可以在HQL中完成)更快,如果仍然需要员工记录,则Overmeulens解决方案具有更好的性能。

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

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