gpt4 book ai didi

java - @OneToMany(EAGER) 与@LazyCollection(FALSE)&OneToMany(LAZY)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:36 30 4
gpt4 key购买 nike

代码之间有什么区别?

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "siteesTypeSite", cascade = CascadeType.ALL,fetch = FetchType.LAZY)
public Set<Sites> getSitees() {
return sitees;
}

@OneToMany(mappedBy = "siteesTypeSite", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
public Set<Sites> getSitees() {
return sitees;
}

对我来说,他们两个都得到了相似的结果,但第二种情况更清晰。如果我记错了请指正。

最佳答案

注释之间的主要区别在于 @OneToMany 是纯 JPA 注释。而 @LazyCollection 是特定于 Hibernate 的。

因此,如果您希望您的代码可以跨各种 JPA 提供程序移植,您应该使用 JPA 注释。

更新

为了解释这两个注释之间的关系,请考虑 Department -> Employee 之间的 OneToMany 关系

案例 1:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "DEPARTMENT_ID")
private List<Employee> employees = new ArrayList<>();

如果您使用以下方法从数据库中获取一个 Department 对象:

entityManager.find(Department.class, 1L);

触发以下查询以获取数据

SELECT department0_.DEPARTMENT_ID AS DEPARTMENT_ID1_0_0_,
department0_.DEPARTMENT_NAME AS DEPARTMENT_NAME2_0_0_,
department0_.LOCATION AS LOCATION3_0_0_,
employees1_.DEPARTMENT_ID AS DEPARTMENT_ID3_1_1_,
employees1_.EMPLOYEE_ID AS EMPLOYEE_ID1_1_1_,
employees1_.EMPLOYEE_ID AS EMPLOYEE_ID1_1_2_,
employees1_.DEPARTMENT_ID AS DEPARTMENT_ID3_1_2_,
employees1_.EMPLOYEE_NAME AS EMPLOYEE_NAME2_1_2_
FROM DEPARTMENT department0_
LEFT OUTER JOIN EMPLOYEE employees1_
ON department0_.DEPARTMENT_ID =employees1_.DEPARTMENT_ID
WHERE department0_.DEPARTMENT_ID=?

所以这意味着它将一次获取单个查询中的所有数据。

案例 2:

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "DEPARTMENT_ID")
private List<Employee> employees = new ArrayList<>();

如果您使用以下方法从数据库中获取 Department 对象,则类似:

entityManager.find(Department.class, 1L);

以下查询被触发以获取数据:

SELECT department0_.DEPARTMENT_ID AS DEPARTMENT_ID1_0_0_,
department0_.DEPARTMENT_NAME AS DEPARTMENT_NAME2_0_0_,
department0_.LOCATION AS LOCATION3_0_0_
FROM DEPARTMENT department0_
WHERE department0_.DEPARTMENT_ID=?

SELECT employees0_.DEPARTMENT_ID AS DEPARTMENT_ID3_1_0_,
employees0_.EMPLOYEE_ID AS EMPLOYEE_ID1_1_0_,
employees0_.EMPLOYEE_ID AS EMPLOYEE_ID1_1_1_,
employees0_.DEPARTMENT_ID AS DEPARTMENT_ID3_1_1_,
employees0_.EMPLOYEE_NAME AS EMPLOYEE_NAME2_1_1_
FROM EMPLOYEE employees0_
WHERE employees0_.DEPARTMENT_ID=?

总结一下,在第一种情况下,因为 FetchTypeEAGER EmployeesDepartment 一起被急切地获取在单个 JOIN 查询中。

还有,

在第二种情况下,Employees 是通过 Department 获取的,但是由于 FetchTypeLAZY,因此单独的查询将被解雇以获取 Employees。如果你删除 @LazyCollection(LazyCollectionOption.FALSE) Employees 根本不会被获取,直到你访问 Department 上的 Employees > 实例。

关于java - @OneToMany(EAGER) 与@LazyCollection(FALSE)&OneToMany(LAZY),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242199/

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