我想使用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吗?
事实证明,过滤条件并不完全支持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之后,但在占位符替换完成之前的查询。至少在版本3中是这样。