如何在Hibernate过滤条件下使用subselect HQL?

时间:2011-07-25 10:35:39

标签: hibernate hql

我想使用Hibernate的过滤器来过滤“MyEntity”对象,在过滤条件中使用“AnotherEntity”选项。配置看起来像这样:

<hibernate-mapping>

  <filter-def name="myFilter" condition="someProperty in (select x.property1 from AnotherEntity x where property2 = :property2)">
    <filter-param name="property2" type="long"/>
  </filter-def>

  <class name="com.example.MyEntity" table="SOME_TABLE">
    <id name="OID" column="O_ID" type="long">
      <generator class="hilo">
        <param name="table">oid_id</param>
        <param name="column">next_id</param>
      </generator>
    </id>
    <version name="hibernateVersion" column="hibernate_version" unsaved-value="negative"/>
    <property name="someProperty"/>
    <filter name="myFilter"/>
  </class>

  <class name="com.example.AnotherEntity" table="ANOTHER_TABLE">
    <composite-id>
      <key-many-to-one name="property1" ... />
      <key-many-to-one name="property2" ... />
    </composite-id>
  </class>

</hibernate-mapping>

它分别给了org.hibernate.exception.SQLGrammarException: could not execute query一个SQLException Table "ANOTHERENTITY" not found,因为生成的SQL语句包含“AnotherEntity”而不是映射表“ANOTHER_TABLE”,好像没有找到映射一样。但是,当我只执行子选择

select x.property1 from AnotherEntity x where property2 = :property2

它运作正常。

我在这里想念什么?我的配置错了吗?我可以在过滤器中使用Suselect HQL吗?

1 个答案:

答案 0 :(得分:4)

事实证明,过滤条件不支持HQL的所有荣耀。您必须使用SQL或更精确地编写WHERE子句片段。这意味着您必须使用表名和列名而不是实体名和属性名。

但是,您可以使用命名占位符。坚持问题中的例子,你会写出这样的条件:

<filter-def name="myFilter" condition="SOME_COLUMN in (select x.COLUMN_X from ANOTHER_TABLE x where COLUMN_Y = :foo)">
    <filter-param name="foo" type="long"/>
  </filter-def>

在HQL被转换为SQL之后但在占位符替换完成之前,似乎这个条件附加到查询中。至少对于Hibernate的3.x版本。