商店产品和类别之间存在多对多关系。多个商店有相同/多个产品。每个产品属于多个类别。我想获得具有给定类别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<>();
并且在类别I中有类似的内容:
@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行。这不是必需的。我该如何避免呢?
答案 0 :(得分:0)
我通过稍微调整查询来解决问题:
sql = "select product from Shop shop" +
" join shop.products product" +
" join product.categories category" +
" where shop.id = :shopId and category.id = :categoryId";