Spring中以List作为参数的多对多JPQL@Query
我有一个简单的产品类别多对多关系,其中产品有一个ListSpring中以List作为参数的多对多JPQL@Query,spring,list,jpa,many-to-many,jpql,Spring,List,Jpa,Many To Many,Jpql,我有一个简单的产品类别多对多关系,其中产品有一个List“categories”属性,类别有一个List“products”属性。JPA ORM映射非常好,并且可以正常工作 在ProductRepository中,我希望包含一个方法,该方法将部分名称和类别列表作为参数,并返回包含给定名称和参数列表中任何类别的所有产品。我的问题是:是否可以在@query中指定我的查询?怎么做 @Repository public interface ProductRepository extends JpaRep
@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
@Query("SELECT obj FROM Product obj WHERE obj.name LIKE %?1 AND obj.categories ?????")
List<Product> findByNameCategories(String name, List<Category> categorias);
}
@存储库
公共接口ProductRepository扩展了JpaRepository{
@查询(“从产品obj中选择obj,其中obj.name,如%.1和obj.categories”)
列出findByNameCategories(字符串名称、列表类别);
}
你就快到了。无需使用@query
注释,您就可以手工创建查询以执行所需操作
List<Product> findByNameStartingWithAndCategoriesIn(String name, Set<Category> categorias);
List findByNameStartingWithAndCategoriesIn(字符串名称,集合分类);
对于不同的结果:
Set<Product> findDistinctByNameStartingWithAndCategoriesIn(String name, Set<Category> categorias);
Set finddistincbynamestartingwithandcategoriesin(字符串名,Set categorias);
Spring将自动为您创建适当的查询。您还可以使用EndingWith
将以%结尾的参数包装起来,或使用Containing
将参数两边都包装成%
我将您的列表categorias
更改为Set,因为列表中可以有重复的Category对象,而Set在幕后创建查询时不会有重复的Category对象,因为in子句中有唯一的id
非常好地使用了标准名称,谢谢。只有一个问题:方法是返回重复的产品。为了得到不同的产品,我将返回类型替换为Set