JPA/Hibernate 查询太多,查询速度慢

JPA/Hibernate Query Slow with too many queries

我有两个实体 EmployeeDepartment

Employee 实体是我的应用程序的只读数据集(我不拥有此 table)

支持我拥有的 Department 实体的 table 数据。如果我在不注释 DepartmentEmployee 实体关系的情况下查询我的 Employee 实体,查询速度超快,因为它只产生一个 SQL 调用。

一旦我将 Department 关系注释到 Employee 实体中,就会有大量的 SQL 调用。以下是我认为有助于获得帮助的每个实体的相关细节:

@Entity
Employee
@Id
String employee_number;
String first_name;
String last_name;
String phone_number;
@Column(name="dept")
private String home_dept_number;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="dept", referencedColumnName="dept_number", insertable = false, updatable = false)
@NotFound(action = NotFoundAction.IGNORE)
private Department department;


@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="dept", referencedColumnName="department_number", insertable = false, updatable = false)

@Entity    
Department
@Id
String dept_number
String dept_name;

@OneToOne(fetch = FetchType.LAZY)
@NotFound(action=NotFoundAction.IGNORE)
@JoinColumn(name = "department_manager_id", referencedColumnName = "employee_number")
private Employee departmentManager;

@OneToOne(fetch = FetchType.LAZY)
@NotFound(action=NotFoundAction.IGNORE)
@JoinColumn(name = "department_admin_aide_id", referencedColumnName = "employee_number")
private Employee departmentAdminAide;

@OneToOne(fetch = FetchType.LAZY)
@NotFound(action=NotFoundAction.IGNORE)
@JoinColumn(name = "department_rep_id", referencedColumnName = "employee_number")
private Employee departmentRepresentative;

我的猜测是速度缓慢是由 @NotFound 注释引起的:Hibernate 可能被迫检查该部门是否真的存在。

使用 @NotFound 是一种黑客手段,用于补偿员工参考不存在的部门的不一致数据库。如果您的数据库是一致的(并且应该由外键约束强制执行),则不需要这些注释。