实现了一对多关系,并且工作正常.
我的问题是当我运行以下查询时,如果该表有100个员工行,并且每个员工有2个部门.数据库查询被调用101次,因为对于每个员工来说它正在调用部门查询,完成调用所有100行需要很长时间,任何人都可以建议任何替代解决方案吗?
请参阅下面的详细信息
它正在调用的查询:
First query is : SELECT * FROM Employee e
Next 100 queries : SELECT * FROM DEPARTMENT d WHERE d.EmployeeId=?
JPA数据库调用:
javax.persistence.Query query = em.createNamedQuery("SELECT * FROM Employee e", Employee.class);
return query.getResultList();
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable
{
@Id
@Column(name = "EmployeeId")
String employeeId;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List departments;
public List getDepartments() {
return departments;
}
public void setDepartments(List departments) {
this.departments = departments;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
}
@Entity
@Table(name = "DEPARTMENT")
public class Department implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "DepartmentID")
String departmentId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "EmployeeId", insertable = false, updatable = false)
private Employee employee;
}
输出xml:
Rob
1
2
Sam
1
2