问题
I have two entities Employee and Department
The Employee entity is a read-only dataset for my application (I don't own this table)
The table data backing the Department Entity I do own. If I query my Employee entity without annotating a Department to Employee entity relationship, the query is superfast because it produces only one SQL call.
As soon as I annotate the Department relationship into the Employee entity, there are a ton of SQL calls. Here are what I think are the pertinent details for each entity to assist in getting help:
@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;
回答1:
My guess is that the slowness is caused by the @NotFound annotations: Hibernate is probably forced to check if the department really exists.
Using @NotFound is a hack to compensate for an inconsistent database where employees reference departments which don't exist. If your database is consistent (and that should be enforced by foreign key constraints), you don't need those annotations.
来源:https://stackoverflow.com/questions/28546577/jpa-hibernate-query-slow-with-too-many-queries