如何在MySql/Jpa上找到一个包含多对多关系中(另一个实体的)id列表的实体



我有3个表:

  • 食谱(id,name(
  • Recipes_Ingredients(id、fk_recipe、fk_ingredient、数量(
  • 成分(id,name(

我需要找到所有包含所提供成分列表的食谱。

Es:

我提供了一份配料清单,如111(盐(、222(胡椒(、333(油(,我需要找到所有包含这些配料的食谱。查询应该会返回所有包含这些成分的食谱。

我还需要一种向Jpa报告查询的方法。

提前感谢!

SELECT fk_recipe
FROM Recipes_Ingredients
WHERE fk_ingredient IN (111,222,333)
GROUP BY fk_recipe
HAVING COUNT(DISTINCT fk_ingredient) = 3

如果需要,加入RecipesIngredients

sql:

select distinct r.fk_recipe
from Recipes_Ingredients r
where r.fk_ingredient in (111,222,333)

在springboot jpa中,您可以使用@Query

@Query("select distinct r.fk_recipe from Recipes_Ingredients r 
where r.fk_ingredient in :ingredients")
List<Long> findRecipe(@Param("ingredients") Set<Long> ingredients);

当您调用findRecipe方法时,创建一个Set作为参数。

最新更新