编程语言
首页 > 编程语言> > java-@OneToMany(EAGER)与@LazyCollection(FALSE)&OneToMany(LAZY)

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

作者:互联网

代码之间有什么区别?

@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->>之间的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=?

综上所述,在第一种情况下,由于FetchType为EAGER,因此在单个JOIN查询中会急切地获取员工和Department.

和,

在第二种情况下,使用Department来获取Employees,但是由于FetchType为LAZY,将触发单独的查询来获取Employees.而且,如果您删除@LazyCollection(LazyCollectionOption.FALSE),直到您访问Department实例上的Employees,都不会再提取Employees.

标签:hibernate,lazy-initialization,java
来源: https://codeday.me/bug/20191026/1940003.html