为什么在本机查询中 Hibernate 延迟加载子实体?

Adr*_*ano 10 hibernate spring-data-jpa

我不明白,当我使用 JPQL 和 JOIN fetch 时,hibernate 应该执行一个查询来连接子实体,但是当我想使用本机查询并使用一个查询连接所有子实体时,hibernate 仍然会延迟加载其他查询中的子实体。我正在使用 Spring Data 2。

我应该如何避免使用本机查询进行延迟加载n+1查询?

例子:

@Query(value = "SELECT recipe.*, r_ing.*, ing.* FROM recipe recipe join " +
        " on recipe.id = r.recipe_id " +
        " LEFT JOIN recipe_ingredients r_ing on r.recipe_id = r_ing.recipe_id " +
        " LEFT JOIN ingredient ing on r_ing.ingredient_id = ing.id where ing.names in (:ingredientsNames)",
        countQuery = "SELECT count(*) FROM recipe recipe join " +
                " on recipe.id = r.recipe_id " +
                " LEFT JOIN recipe_ingredients r_ing on r.recipe_id = r_ing.recipe_id " +
                " LEFT JOIN ingredient ing on r_ing.ingredient_id = ing.id where ing.names in (:ingredientsNames)",
        nativeQuery = true
)
Page<Recipe> findAllByIngredientsNames(List<String> ingredientsNames, Pageable page);
Run Code Online (Sandbox Code Playgroud)

实体:

@Entity
public class Recipe {
    @OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<RecipeIngredients> ingredients;
}
@Entity
public class RecipeIngredients implements Serializable {

    @EmbeddedId
    private RecipeIngredientsId recipeIngredientsId;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("recipeId")
    private Recipe recipe;

    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @MapsId("ingredientId")
        private Ingredient ingredient;
}

@Entity
public class Ingredient {

    @NaturalId
    @Column(unique = true)
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

Ily*_*hin 10

对于本机查询,Hibernate 不知道如何映射高级数据。在您的情况下,您有一个获取Recipe实体的请求,其中实体映射器知道如何从 中提取结果SELECT * FROM recipe。但ingredientsproperty是反向映射,它被实现为一个惰性初始化集合,后面有查询。这就是 JPA 和 Spring 数据为您所做的,但它们不够智能,无法自动理解并进一步映射它以急切地将查询结果映射到集合属性。

另外,我猜您在查询结果中看到了多个相同的Recipe实体。

如果出于某种原因您确实想要处理本机查询,那么只需正确使用它们即可:本机查询的结果通常不是 JPA 管理的实体,而是投影。

因此,创建您在本机查询中拥有的行的特定投影:

public class FullRecipeProjection {
    private final Integer recipeId; 
    private final Integer recipeIngredientsId;
    private final Integer ingredientId
    private final Integer ingredientName 

    /* Full-arg-constructor */
    public FullRecipeProjection (Integer recipeId, Integer recipeIngredientsId, Integer ingredientId, String ingredientName) {...}

}
Run Code Online (Sandbox Code Playgroud)

然后您可以创建查询:

@Query(value = "SELECT new FullRecipeProjection(recipe.recipeId, r_ing.recipeIngredientsId, ing.ingredientId, ing.IngredientName) FROM recipe recipe join " +
        " on recipe.id = r.recipe_id " +
        " LEFT JOIN recipe_ingredients r_ing on r.recipe_id = r_ing.recipe_id " +
        " LEFT JOIN ingredient ing on r_ing.ingredient_id = ing.id where ing.names in (:ingredientsNames)",
        countQuery = "SELECT count(*) FROM recipe recipe join " +
                " on recipe.id = r.recipe_id " +
                " LEFT JOIN recipe_ingredients r_ing on r.recipe_id = r_ing.recipe_id " +
                " LEFT JOIN ingredient ing on r_ing.ingredient_id = ing.id where ing.names in (:ingredientsNames)",
        nativeQuery = true
)
List<FullRecipeProjection> findAllByIngredientsNames(List<String> ingredientsNames);
Run Code Online (Sandbox Code Playgroud)

然后您可以将 的集合转换FullRecipeProjection为 的类似对象Recipe

public class FullRecipe {
    private final Integer recipeId;
    private final Set<IngredientProjection> ingredients;
    public FullRecipe(Integer recipeId, Set<IngredientProjection> ingredients) {...}
}

public class IngredientProjection {
    private final Integer ingredientId;
    private final String ingredientName;
    public IngredientProjection(Integer ingredientId, String ingredientName) {...}
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以得到你想要的东西,如下所示:

final List<FullRecipeProjection> data = repository.findAllByIngredientsNames(ingredientsNames);

final List<FullRecipe> results = data
    .stream()
    // extracting distinct identities of recipes, you have fetched  
    .map(FullRecipeProjection::recipeId)
    .distinct()
    // now we have unique key for the data and can map it
    .map(it -> 
         new FullRecipe(
             it, 
             // extracting all ingredients, which  were fetched in rows with references to recipe.
             data
                 .stream()
                 .filter(o -> o.recipeId.equals(it))
                 .map(ing -> new IngredientProjection(ing.ingredientId, ing.ingredientName))
                 .collect(Collectors.toSet())
    .collect(Collectors.toList()) ; 
Run Code Online (Sandbox Code Playgroud)

相当长的路。但这就是它的工作原理。当您使用 JPQL 查询时,这个长时间的处理是由 Hibernate 完成的。

请注意:对于这种数据提取,分页变得很麻烦:按照您指定的方式,您将不会对最终结果进行分页,而是对 进行分页FullRecipeProjection,这可能会导致不完整的Recipe获取,并且肯定会导致分页数据错误(它可能只包含 1 FullRecipe,它可能无法完全加载!)。