[英]Wrong result set with Many-to-Many JPQL
我在商店產品和類別之間存在多對多關系。 多家商店有相同/多種產品。 每個產品都屬於多個類別。 我想獲取特定商店中具有給定類別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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.