Hibernate version: Hibernate 3.2.6ga
Name and version of the database you are using: MySQL
Hi,
I have the following relationships:
Code:
1) Client 1-M Entity (a Client has many Entities, an Entity belongs to a Client, bi-directional)
2) Entity 1-1 User (an Entity can have a User, a User belongs to an Entity, bi-directional.)
3) User M-M Rol (a User has many Roles, a Rol can be assigned to many users, unidirectional to the right)
So, an Object would be something like this:
Code:
client
- entities (NOTE: an entity can have a user, it's optional)
- user
- roles (ROLE1, ROLE2, or ROLE3)
* There are clients that have entities, and there are some clients that don't have any entity.
* Some clients that have entities have a user assigned to it, and there're some entities that don't have assigned a user.
I need to request an specific client. Also I need to fetch their entities that have assigned a user with an specific role. For example:
Request Client #22, and all entities with users assigned to ROLE1.
Case A) If the client requested doesn't have any entities with the requested role, then it must return a Client object with an empty collection of entities.
Case B) If the client requested does have entities (some may have assigned a user with the requested role and some others with a role different from the requested), then it must return a Clien object with the collection of entities that have the role requested.
The Query I have right now is the following:
Code:
Query q = getSession()
.createQuery("select c from Client as c " +
"left join fetch c.entities as e " +
"left join e.user.roles as r " +
"where c.id=:cid and r.id IN ('ROLE1') " +
"order by e.name asc)")
.setParameter("cid", id);
It works well for case B... For case A, it returns a null client object.
I also tried filtering the collection in User mapping file:
Code:
... User.hbm.xml file
<bag name="roles" table="USER_ROL">
<key column="USER_ID"/>
<many-to-many class="Rol" column="ROL_ID"/>
<filter name="myFilter" condition=":myRol = ROL_ID"/>
</bag>
...
This filter returns all entities but don't return Roles that are different from the requested rol. So, it doesn't work for me.
Does anyone have any idea about how to filter a collection given this scenario?
Thanks in advance :)