Hibernate HQL。 ManyToMany在子查询中

时间:2015-11-26 04:50:49

标签: java hibernate

我有以下实体:

@Entity
public class Company {
   ....
   @OneToMany
   private List<Product> products = new Arraylist<>();           
   ....
}

@Entity
public class Product {
   ....
   @Column(name="product_key")
   private String productKey; // same value as in ProductCategory
   ....
}

@Entity
public class ProductCategory{
   ....
   @Column(name="product_key")
   private String productKey // same value as in Product
   @ManyToMany 
   @JoinTable (...)
   private List<Category> categories = new ArrayList<>();

   ....
}

我想编写一个查询,它将返回具有相应类别的公司:

Company - List<Category>

即。我想要每个产品公司的聚合类别。

目前我最终得到了这个HQL查询,但它不起作用:

SELECT DISTINCT c, 
        (SELECT pc.categories 
         FROM ProductCategories pc 
         LEFT JOIN c.products products
         WHERE pc.productKey IN products.productKey) 
FROM Company c

我尝试使用List<Categories>Company实体添加虚拟@JoinFormula字段,但没有成功(@JoinFormula不能与List类型一起使用,只能使用单个值)

1 个答案:

答案 0 :(得分:0)

我认为你的数据库设计正在使解决方案变得困难。

自公司&amp;产品有一对多的关系,关系的所有者应该是产品。因此,您可以在每个产品中保留对公司的引用。

如果我是你,我会选择这样的设计。

公司类

@Entity
public class Company {
    @OneToMany(mappedBy="company", cascade = CascadeType.ALL)
    private List<Product> products = new ArrayList<Product>();

    @Id
    private int companyId;

}

产品类

@Entity
public class Product {
    @Id
    @Column(name = "product_key")
    private String productKey; // same value as in ProductCategory

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "company", nullable = false)
    private Company company;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy="products")
    private List<ProductCategory> categories = new ArrayList<ProductCategory>();
}

ProductCategory Class

 @Entity
    public class ProductCategory {                      

        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name="ProductWiseCategory", joinColumns=@JoinColumn(name="cat_name"),
                  inverseJoinColumns=@JoinColumn(name="product_key") )
        private List<Product> products = new ArrayList<Product>();