我有很多到许多商店产品和类别之间的关系。多家商店有相同/多种产品。每个产品都属于多个类别。我想得到的产品清单在一个特定的商店与给定的类别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行。这不是必需的。我怎样才能避免呢?
发布于 2017-11-05 06:24:20
我通过稍微修改查询来解决这个问题:
sql = "select product from Shop shop" +
" join shop.products product" +
" join product.categories category" +
" where shop.id = :shopId and category.id = :categoryId";https://stackoverflow.com/questions/47118354
复制相似问题