简体   繁体   English

在 Spring 中以 List 作为参数的多对多 JPQL @Query

[英]Many to many JPQL @Query with List as argument in Spring

I've got a simple Product-Category many-to-many relationship, where Product has a List< Category> "categories" attribute, and Category has a List< Product> "products" attribute.我有一个简单的 Product-Category 多对多关系,其中 Product 有一个 List< Category> "categories" 属性,而 Category 有一个 List< Product> "products" 属性。 JPA ORM mapping is pretty ok and working. JPA ORM 映射非常好并且工作正常。

In the ProductRepository, I'd like to include a method that takes a partial name and a list of Category as parameter, and returns all products that contain the given name and any of the categories in the parameter list .在 ProductRepository 中,我想包含一个方法,该方法采用部分名称和 Category 列表作为参数,并返回包含给定名称和参数列表中任何类别的所有产品。 My question is: is it possible to specify my query inside a @Query?我的问题是:是否可以在 @Query 中指定我的查询? How?如何?

@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);
}

You are almost there.你快到了。 You can craft your query to do what you want without having to use the @Query annotation您可以制作查询以执行您想要的操作,而无需使用@Query批注

List<Product> findByNameStartingWithAndCategoriesIn(String name, Set<Category> categorias);

For distinct results:对于不同的结果:

Set<Product> findDistinctByNameStartingWithAndCategoriesIn(String name, Set<Category> categorias);

Spring will automatically create the proper query for you. Spring 会自动为您创建正确的查询。 You can also you EndingWith to wrap the parameter ending with % or Containing to have the parameter be wrapped on both sides with %您也可以使用EndingWith来包装以 % 结尾的参数,或者Containing将参数用 % 包装在两侧

I changed your List<Category> categorias to a Set because list can have duplicate Category objects in the list while a Set will not so when it crafts the query behind the scenes you'll have unique ids in the In clause.我将您的List<Category> categorias更改为 Set,因为列表中可以有重复的 Category 对象,而 Set 不会这样,当它在幕后制作查询时,您将在 In 子句中拥有唯一的 id。

Spring Documentation on crafting queries 关于制作查询的 Spring 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM