将Spring数据JPA EntityGraph与LAZY加载模式一起用于NamedAttributeNode字段

我面临2个问题:N + 1个查询和内存不足(OOM)。

我通过分页和延迟加载解决了OOM:

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Set<Employee> employees;

But when I use lazy loading, N + 1 query happened. So I try to use EntityGraph as https://www.baeldung.com/spring-data-jpa-named-entity-graphs. But as my researches and local test, EntityGraph always do eager loading for NamedAttributeNode field - association field, which I want to be lazy loading:

@NamedEntityGraph(name = "Department",
        attributeNodes = {
                @NamedAttributeNode("employees")
})

So are there any way to get them both ? Use EntityGraph to avoid N + 1 and lazy loading to avoid OOM ?

评论
  • ab_non
    ab_non 回复

    Using EntityGraph all your NamedAttributeNode associations will be loaded in 1 query with Join clause. Enable sql log to see how many queries hibernate does for loading entities in different scenarios

    logging.level.org.hibernate.SQL=DEBUG
    

    You will see that using @OneToMany(fetch = FetchType.EAGER) without EntityGraph it does separate select for each Employee, but using EntityGraph it performs only 1 `select

    同样不要忘记在存储库中指定实体图名称,例如:

    @EntityGraph(value = "Department")
    List<Department> findAll();