【问题标题】:How to use subselect HQL in a Hibernate filter condition?如何在休眠过滤条件中使用子选择 HQL?
【发布时间】:2011-07-25 10:35:38
【问题描述】:

我想使用 Hibernate 的过滤器来过滤“MyEntity”对象,在过滤条件中使用“AnotherEntity”的 suselect。配置如下所示:

<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 吗?

【问题讨论】:

  • 我也有同样的问题。你找到解决办法了吗?
  • 我创建了一个答案,见下文。我认为您必须编写 SQL,因为不支持 HQL。

标签: hibernate hql


【解决方案1】:

事实证明,过滤条件并不完全支持 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 版本。

【讨论】:

  • 是否可以使用休眠过滤器根据连接表的列值进行连接和过滤记录?
  • 很抱歉,我没有设置,无法试用。但我认为过滤器只是添加到结果 SQL 的 where 子句中,所以它可能会起作用。
  • 看起来休眠过滤器不允许我根据连接表的列值进行过滤。请参阅hibernate.atlassian.net/browse/HHH-298
猜你喜欢
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2017-04-17
  • 2012-02-12
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 2011-05-05
相关资源
最近更新 更多