有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java错误的结果集,包含许多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行。这不是必须的。我怎样才能避免呢


共 (1) 个答案

  1. # 1 楼答案

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

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