为什么Hibernate在提交时发出了两个select count语句

时间:2015-08-17 21:51:58

标签: java hibernate

假设以下两个实体。我在使用Bag语义时避免在向部门添加新员工时加载整个员工集合。

public class Department {
   @Column(name = "department_id")
   private long id;
   @Column
   private String nombre;

   @OneToMany(mappedBy = "department", cascade = CascadeType.PERSIST)
   private Collection<Employee> employees;

   public void addEmployee(String nombreEmployee) { 
       Employee e = new Employee(nombreEmployee);
       this.employees.add(e);
       e.setDepartment(this);
   }

}

public class Employee {
    @Column(name = "employee_id") 
    private long id;
    @Column
    private String nombre;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
}

public class Main {
  public static void main(String args[]) {            
     //all hibernate stuff    
     Department d = session.get(Department.class, 1l);
     d.addEmployee("John Doe");
     tx.commit();
  }

}

有效。它插入新员工(由于cascade.persist),deparment_id填充到正确的员工。但是,在tx.commit()之后,Hibernate发出了两个这样的语句:&#34;从员工中选择count(employee_id),其中deparment_id =?&#34;

为什么Hibernate需要这样做?

(如果我删除Cascade,我可以避免这两个count语句,并调用session.save(employee),但重点是需要两个count语句)

0 个答案:

没有答案