【发布时间】:2020-06-02 07:55:03
【问题描述】:
我不明白,当我使用 JPQL 和 JOIN fetch 时,休眠应该执行一个查询来连接子实体,但是当我想使用本机查询并通过一个查询连接所有子实体时,休眠仍然会在其他查询中延迟加载子实体. 我正在使用 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);
实体:
@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;
}
【问题讨论】:
-
请添加您的控制器/服务代码,如果您使用任何 dto 进行响应,请也添加它。此外,请尝试使用最少的代码来重现您的问题。