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

Tim*_*the 5 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>
Run Code Online (Sandbox Code Playgroud)

这给了我一个org.hibernate.exception.SQLGrammarException: could not execute querySQLException Table "ANOTHERENTITY" not found,因为生成的SQL语句包含"AnotherEntity"而不是映射表"ANOTHER_TABLE",好像没有找到映射一样.但是,当我执行subselect时

select x.property1 from AnotherEntity x where property2 = :property2
Run Code Online (Sandbox Code Playgroud)

它只是工作正常.

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

Tim*_*the 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>
Run Code Online (Sandbox Code Playgroud)

看起来这个条件是在 HQL 转换为 SQL 之后但在占位符替换完成之前附加到查询的。至少对于 Hibernate 3.x 版本是这样。