简体   繁体   中英

How many hit to database for one-to-many query using hibernate?

I am having one-to-many relationship between Employee and Department and my class is looking like :

@Entity
public class Employee {
@Id
private int empId;
private String empName;
@OneToMany
@JoinTable (name = "relationalTable" , joinColumns = @JoinColumn(name = "empId"),inverseJoinColumns=@JoinColumn(name = "deptId"))
private Collection <Department> dept = new ArrayList<Department>();

public int getEmpId() {
    return empId;
}
public void setEmpId(int empId) {
    this.empId = empId;
}

public Collection<Department> getDept() {
    return dept;
}
public void setDept(Collection<Department> dept) {
    this.dept = dept;
}


@Column 
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}
}

and my department class like :

@Entity
public class Department {
   int deptId;
   String deptName;
   private Employee emp;

   @ManyToOne
   public Employee getEmp() {
      return emp;
   }

   public void setEmp(Employee emp) {
      this.emp = emp;
   }

   @Id
   public int getDeptId() {
      return deptId;
   }

   public void setDeptId(int deptId) {
      this.deptId = deptId;
   }

   @Column
   public String getDeptName() {
      return deptName;
   }

   public void setDeptName(String deptName) {
      this.deptName = deptName;
   }
}

If I fetch the Department. So it will fetch all the employee at the same time associated with it. say with department id 1 there are 1000 employee. So how many queries will execute at this time to database to fetch all the data?

IF the fetchType was Lazy Hibernate retrieve the record when you try to access the departments

If its eager Hibernate join all the queries into one queries and execute one query.

If you haven't specified the fetch type, then one-to-many relationships are by default lazy loaded. so your Employee class has one to many Departments.

so if you u load 1000 Employees, then there will be 1000 calls to load departments (1 call per each Employee).

what i cant understand your relationships,in this organization one department can have only one Employee but one Employee can work on few departments which is strange.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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