计算行的数量很多,以在Hibernate中多关系(Count the number of rows

2019-10-17 09:47发布

我有三个许多表的甲骨文(10G)数据库,如下所示。 我使用休眠工具3.2.1.GA使用Spring 3.0.2版。

  1. 产品 -父表
  2. 颜色 -父表
  3. ProductColour -连接表-引用colourIdprodIdColourProduct表分别

ProductColour之间连接表 ProductColour 。 如表名称所暗示的,之间是有很多一对多的关系, ProductProductColour 。 我认为,在数据库中的关系,可以很容易地想象中的很清楚,只有这么多的信息。 因此,我不打算去探索在长度这种关系。

在一个实体(行) Product与任何数量的实体相关联的Colour在和一个实体(行) Colour也可以与任意数量的实体相关联的Product


比方说,作为一个例子,我需要计算在可用的行数Product表(关于休眠),这是可以做到像下面这样。

Object rowCount = session.createCriteria(Product.class)
                  .setProjection(Projections.rowCount()).uniqueResult();

如果我需要在计算可用的行数ProductColour表? 因为,它是一个多一对多的关系,它被映射在ProductColour实体类(POJO)中与有相应的java.util.Set并没有直接的POJO类的ProductColour表可用。 因此上述行计数说法似乎并不在这种情况下工作。

有没有算在Hibernate中这样的加盟实体的行数以精确的方式?

Answer 1:

我想你应该能够做到沿线一个JPQL或HQL。

SELECT count(p.colors) FROM Product AS p WHERE p.name = :name ... other search criteria etc 

要么

SELECT count(c.products) FROM Color AS c WHERE c.name = :name .... other search criteria 

从下面评论,这应该工作:

Long colours=(Long) session.createQuery("select count(*) as cnt from Colour colour where colour.colourId in(select colours.colourId from Product product inner join product.colours colours where product.prodId=:prodId)").setParameter("prodId", prodId).uniqueResult();


文章来源: Count the number of rows in many to many relationships in Hibernate