代码之家  ›  专栏  ›  技术社区  ›  sfussenegger

按类层次结构映射表中的鉴别器值分组

  •  4
  • sfussenegger  · 技术社区  · 14 年前

    Is it possible to write a HQL query that groups results by the discriminator value of a table per class hierarchy mapping? 例如

    "select discriminator d, count(*) c from Foo group by discriminator"
    

    用一个像

    <hibernate-mapping>
      <class abstract="true" name="Foo">
        <!-- SNIP -->
        <subclass name="Bar" discriminator-value="BAR">
          <!-- SNIP -->
        </subclass>
        <subclass name="Baz" discriminator-value="BAZ">
          <!-- SNIP -->
        </subclass>
      </class>
    </hibernate-mapping>
    

    可能的结果是

    +-----+---+
    | d   | c |
    +-----+---+
    | BAR | 3 |
    | BAZ | 4 |
    +-----+---|
    

    所以我要找的是一个有效的替代品 discriminator 在我的HQL查询中。是否有这样的事情,或者我必须使用原始SQL?

    1 回复  |  直到 14 年前
        1
  •  6
  •   Guillaume    14 年前

    这个 class 属性:来自Hibernate文档

    The special property class accesses the discriminator value of an instance in the case of polymorphic persistence. 嵌入在WHERE子句中的Java类名将被转换为其鉴别器值。

    来自cat cat,其中cat.class=domesticcat

    显然,在使用class属性时,至少在我使用的hibernate版本中,有必要使用别名来引用实体。 所以你的HQL请求应该是:

    select f.class, count(*) c from Foo f group by f.class
    

    这将返回包含“bar”和“baz”的数组及其各自的计数。