多对多 JPQL 的错误结果集

Wrong result set with Many-to-Many JPQL

我在商店产品和类别之间建立了多对多关系。多家商店有 same/multiple 种产品。每个产品属于多个类别。我想获取具有给定类别 ID 的特定商店中的产品列表。

        sql = "select shop.products as products from Shop shop" +
                " join shop.products product" +
                " join product.categories category" +
                " where shop.id = :shopId and category.id = :categoryId";

商店有类似的东西:

@ManyToMany(mappedBy = "shops")
private List<Product> products;

产品有:

@ManyToMany
@JoinTable(name = "Products_Categories", joinColumns = {@JoinColumn(name = "Product_ID")},
        inverseJoinColumns = {@JoinColumn(name = "Category_ID")})
private Set<Category> categories;

@ManyToMany
@JoinTable(name = "Shop_Product", joinColumns = {@JoinColumn(name = "Product_ID")},
        inverseJoinColumns = {@JoinColumn(name = "Shop_ID")})
private Set<Shop> shops = new HashSet<>();

在类别中我有类似的东西:

@ManyToMany(mappedBy = "categories")
private List<Product> products;

但是上面查询的结果集包含所有数据,与提供的类别无关。

生成SQL

select product6_.id as id1_4_, product6_.calories as calories2_4_, product6_.createdDate as createdD3_4_, product6_.description as descript4_4_, product6_.modifiedDate as modified5_4_, product6_.name as name6_4_, product6_.price as price7_4_ from Shop shop0_
  inner join Shop_Product products1_ on shop0_.id=products1_.Shop_ID
  inner join Products product2_ on products1_.Product_ID=product2_.id
  inner join Products_Categories categories3_ on product2_.id=categories3_.Product_ID
  inner join Categories category4_ on categories3_.Category_ID=category4_.id
  inner join Shop_Product products5_ on shop0_.id=products5_.Shop_ID
  inner join Products product6_ on products5_.Product_ID=product6_.id where
  shop0_.id=? and category4_.id=?

更新:问题是因为生成的 sql 有额外的连接。检查 SQL 中的第 6 行和第 7 行。那不是必需的。我怎样才能避免它?

我通过稍微调整查询解决了这个问题:

        sql = "select product from Shop shop" +
                " join shop.products product" +
                " join product.categories category" +
                " where shop.id = :shopId and category.id = :categoryId";