如何在 MySql/Jpa 上的多对多关系中找到包含(另一个实体的)id 列表的实体?
How to find an entity containing a list of id (of the other entity) in a many-to-many relation on MySql/Jpa?
我有 3 个表:
- 食谱(id、名称)
- Recipes_Ingredients(id, fk_recipe, fk_ingredient, 数量)
- 成分(id、名称)
我需要找到包含所提供成分列表的所有食谱。
Es:
我提供了一个成分列表,如 111(盐)、222(胡椒)、333(油),我需要找到包含这些成分的所有食谱。查询应该 return me all those recipes that containing these ingredients.
我还需要一种方法将查询报告回 Jpa。
提前致谢!
SELECT fk_recipe
FROM Recipes_Ingredients
WHERE fk_ingredient IN (111,222,333)
GROUP BY fk_recipe
HAVING COUNT(DISTINCT fk_ingredient) = 3
如果需要,加入 Recipes
和 Ingredients
。
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 作为参数。
我有 3 个表:
- 食谱(id、名称)
- Recipes_Ingredients(id, fk_recipe, fk_ingredient, 数量)
- 成分(id、名称)
我需要找到包含所提供成分列表的所有食谱。
Es:
我提供了一个成分列表,如 111(盐)、222(胡椒)、333(油),我需要找到包含这些成分的所有食谱。查询应该 return me all those recipes that containing these ingredients.
我还需要一种方法将查询报告回 Jpa。
提前致谢!
SELECT fk_recipe
FROM Recipes_Ingredients
WHERE fk_ingredient IN (111,222,333)
GROUP BY fk_recipe
HAVING COUNT(DISTINCT fk_ingredient) = 3
如果需要,加入 Recipes
和 Ingredients
。
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 作为参数。