避免在 QueryDSL、Hibernate 和 Spring Data JPA 中加载惰性集合
Avoiding loading of Lazy Collections in QueryDSL, Hibernate and Spring Data JPA
我想在 运行 使用 QueryDSL 进行查询时避免加载一些惰性集合。
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id", nullable = false)
@NotNull
private String id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "employee")
@Fetch(FetchMode.JOIN)
@JsonManagedReference
private Set<Department> departments = new HashSet<Department>();
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "employee")
@Fetch(FetchMode.JOIN)
private Set<Location> locations= new HashSet<Locations>();
}
现在,如果我使用以下查询
final QEmployee employee = QEvent.employee;
final List<Employee> employees = query.from(employee)
.distinct()
.leftJoin(event.departments).fetch()
.list();
现在,Department
table 已正确连接,但它正在为 Location
执行 N+1 选择。我正在使用上述查询的结果来构建 DTO,因此 JSON 没有被触发。在逻辑上,我没有访问 locations,所有位置 + 它下面的所有树仍然被懒惰地获取。如何防止使用 QueryDSL 获取位置。
问题是位置顶部的 @Fetch(FetchMode.JOIN)
注释。我删除了它并且它工作正常。现在无法获取位置。
我想在 运行 使用 QueryDSL 进行查询时避免加载一些惰性集合。
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@Column(name = "id", nullable = false)
@NotNull
private String id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "employee")
@Fetch(FetchMode.JOIN)
@JsonManagedReference
private Set<Department> departments = new HashSet<Department>();
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "employee")
@Fetch(FetchMode.JOIN)
private Set<Location> locations= new HashSet<Locations>();
}
现在,如果我使用以下查询
final QEmployee employee = QEvent.employee;
final List<Employee> employees = query.from(employee)
.distinct()
.leftJoin(event.departments).fetch()
.list();
现在,Department
table 已正确连接,但它正在为 Location
执行 N+1 选择。我正在使用上述查询的结果来构建 DTO,因此 JSON 没有被触发。在逻辑上,我没有访问 locations,所有位置 + 它下面的所有树仍然被懒惰地获取。如何防止使用 QueryDSL 获取位置。
问题是位置顶部的 @Fetch(FetchMode.JOIN)
注释。我删除了它并且它工作正常。现在无法获取位置。