gpt4 book ai didi

java - JPA一对多关系查询

转载 作者:搜寻专家 更新时间:2023-10-31 19:46:11 24 4
gpt4 key购买 nike

实现了一对多关系,并且运行良好。

我的问题是当我运行下面的查询时,如果表有 100 行员工,并且每个员工有 2 个部门。数据库查询被调用了101次,因为每个员工都在调用部门查询,需要很长时间才能完成调用所有一百行,有人可以提出任何替代解决方案吗?

详情请见下方

它正在调用的查询:

    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<Department> departments;

public List<Department> getDepartments() {
return departments;
}

public void setDepartments(List<Department> 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:

        <Employees>
<Employee>
<name>Rob</name>
<Departments>
<Departmnet><id>1</id></Departmnet>
<Departmnet><id>2</id></Departmnet>
</Departments>
</Employee>
<Employee>
<name>Sam</name>
<Departments>
<Departmnet><id>1</id></Departmnet>
<Departmnet><id>2</id></Departmnet>
</Departments>
</Employee>
</Employees>

最佳答案

这是一个典型的 N+1 selects issue .我通常使用 JOIN FETCH 查询来解决这个问题 described herehere

关于java - JPA一对多关系查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22221006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com