2011-07-25 95 views
5

我想用Hibernate的過濾器來過濾「MyEntity」對象,在過濾條件中使用suselect的AnotherEntity。配置看起來是這樣的:如何在Hibernate過濾條件中使用subselect HQL?

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

+0

我有同樣的問題。你找到解決方案嗎? – Saffar

+0

我創建了一個答案,見下文。我認爲你必須編寫SQL,因爲不支持HQL。 –

回答

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版本。

+0

是否可以使用hibernate過濾器基於連接表的列值進行連接和過濾記錄? –

+0

對不起,但我沒有設置,不能試用。但我認爲過濾器只是添加到生成的SQL的where子句中,因此它可能工作。 –

+1

看起來像hibernate filtes不會讓我根據已連接表的列值進行過濾。請參閱https://hibernate.atlassian.net/browse/HHH-298 –

相關問題