Java JPA通过Ingredient id查询Recipe的findBy方法报错如何解决
问题原因
你原来的方法名没有明确分隔嵌套属性层级,Spring Data JPA会优先尝试查找Recipe类下名为recipeIngredientsIngredientId的直接属性,找不到就会抛出异常。
解决方案
可选择以下任意一种方式实现需求:
方法1:使用方法名自动推导
通过下划线_明确分隔嵌套属性层级,避免框架误解析属性名,正确写法如下:
// 下划线可选,用来明确属性层级,减少解析歧义 List<Recipe> findByRecipeIngredients_Ingredient_Id(Long ingredientId);
如果要保留Equal匹配后缀也可以写成:
List<Recipe> findByRecipeIngredients_Ingredient_IdEqual(Long ingredientId);
方法2:使用@Query显式定义JPQL查询
这种方式可读性更高,也不会因为方法名过长出现拼写错误,写法如下:
import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; // 加DISTINCT避免同个Recipe匹配多个配料时返回重复数据 @Query("SELECT DISTINCT r FROM Recipe r JOIN r.recipeIngredients ri WHERE ri.ingredient.id = :ingredientId") List<Recipe> findAllByIngredientId(@Param("ingredientId") Long ingredientId);
内容的提问来源于stack exchange,提问作者hamwac5
相关产品推荐
相关产品推荐

