Hibernate query filter on collection

2019-07-20 10:59发布

问题:

I want to execute following query:

from Item i where i.categoryItems.catalogId = :catId

That however yields in following exception: illegal attempt to dereference collection So I googled, found this Hibernate forum post https://forum.hibernate.org/viewtopic.php?p=2349920 that recommended me to do the following:

from Item i, IN (i.categoryItems) WHERE i.catalogId = :catId

This kind of works, but there's a problem with this: It returns me an Object array with Item object and CategoryItem object. I'm only interested in the single Item object (List)

My mapping of 'Item':

<hibernate-mapping package="be.xx.xx.xx.xx.domain" default-access="field">
  <class name="Item" table="ITEM">  
    <id name="articleId" column="article_id" type="long">
        <generator class="assigned" />
    </id>
...
...
        <set name="categoryItems" table="CATEGORY_ITEM">
            <key column="item_id" />
            <one-to-many class="be.xx.xx.xx.xx.domain.CategoryItem" />
    </set>
</class>
</hibernate-mapping>

Anybody got any ideas?

Thanks

回答1:

Try:

SELECT i FROM Item i inner join i.categoryItems cat WHERE cat.id = :catID

Explanation: The navigation you have tried: i.categoryItems.catalogId works only for 1:1 or n:1 relations, but not for 1:n. -- For 1:n you have to use the explicite join operation.