Hibernate query: does a Set contains a certain Object?

sockeqwe picture sockeqwe · Feb 2, 2012 · Viewed 25.6k times · Source

I have two Hibernate data object. The first is a User (with unique id, username etc.) and the second is the class Collaborateable. Between this two there is a n-to-m relation (implementet with Sets). That means, a User works on many Collaborateables and a Collaborateable has many users. In addition a Collaborateable has exactly one User as owner.

<class name="CollaborateableImpl" table="Collaborateable">
<id name="id" type="int" column="id">
    <generator class="increment" />
</id>

<property name="name" column="name" type="string" not-null="true" />
<property name="keywords" column="keywords" type="string"/>

<!-- Collaborateable has a Registered User as owner -->
<many-to-one name="owner" class="UserImpl" fetch="select">
        <column name="User_id_owner" not-null="true" />
</many-to-one>

<!-- Users that collaborate on this Collaborateable -->
<set name="users" table="CollaborateOn" inverse="false">        
        <key column="Collaborateable_id" />         
        <many-to-many column="User_id" class="UserImpl" />    
</set>

i would like to implement a Hibernate query, that searches for Collaborateables that have a certain user as owner OR containing the same certain User in the Collaborateable.users Set. In addition, there should also be a simple WHERE clause to check for Keywords.

Is there something like a CONTAINS operator in Hibernate?

For example:

FROM CollaborateableImpl WHERE (owner = :user OR users CONTAINS :user) AND keywords like '%:searchString%'

Otherwise, do you know how to solve this problem with a join?

Answer

driangle picture driangle · Feb 2, 2012

You're looking for the elements keyword.

select c 
FROM CollaborateableImpl c 
WHERE (
    c.owner = :user 
    OR :user in elements(c.users)
)
AND c.keywords like '%:searchString%'