簡體   English   中英

Hibernate - 如何在沒有 N+1 的情況下獲取另一個@OneToMany 惰性集合中的@OneToMany 惰性集合

[英]Hibernate - how to fetch @OneToMany lazy collection inside another @OneToMany lazy collection without N+1

我有這樣的東西

Entity1
@Id
String id1;
@OneToMany(Fetch = LAZY)
List<Entity2> list1;
...

Entity2
@Id
String id2;
@OneToMany(Fetch = LAZY)
List<Entity3> list2;
...

Entity3
@Id
String id3;
...

我想在同一個 session 中初始化 list1 和 list2。我被困在

entity1 = (Entity1) session
                    .createCriteria(Entity1.class)                    
                    .setFetchMode("list1", FetchMode.JOIN)
                    .uniqueResult();

我想不出一種正確的方法來初始化 Entity2 的第二個嵌套列表,而不使用 Hibernate.initialize 並導致 N+1 查詢或使用 EAGER。

首先,不要使用遺留的 Hibernate 條件 API。它已被棄用並在 Hibernate 6 中被刪除。

您可以使用連接提取獲取第一個集合,使用@Fetch(FetchMode.SUBSELECT)提取獲取第二個集合,但我認為這是Blaze-Persistence Entity Views的完美用例。

我創建了庫以允許在 JPA 模型和自定義接口之間輕松映射或抽象 class 定義的模型,類似於類固醇上的 Spring 數據投影。 這個想法是,您按照自己喜歡的方式定義目標結構(域模型),並通過 JPQL 表達式將 map 屬性(getter)定義為實體 model。

對於您的用例,DTO model 對於 Blaze-Persistence 實體視圖可能如下所示:

@EntityView(Entity1.class)
public interface Entity1Dto {
    @IdMapping
    Long getId();
    String getName();
    @Mapping(fetch = MULTISET)
    Set<Entity2Dto> getRoles();

    @EntityView(Entity2.class)
    interface Entity2Dto {
        @IdMapping
        Long getId();
        String getName();
        @Mapping(fetch = MULTISET)
        Set<Entity3Dto> getRoles();
    }
    @EntityView(Entity3.class)
    interface Entity3Dto {
        @IdMapping
        Long getId();
        String getName();
    }
}

MULTISET提取將聚合所有子行,從而避免 N + 1 問題。 另請參閱文檔以獲取更多信息。

查詢是將實體視圖應用於查詢的問題,最簡單的就是通過 id 進行查詢。

Entity1Dto a = entityViewManager.find(entityManager, Entity1Dto.class, id);

Spring 數據集成允許您幾乎像 Spring 數據投影一樣使用它: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<Entity1Dto> findAll(Pageable pageable);

最好的部分是,它只會獲取實際需要的 state!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM