-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: HQL for exists (select 1 from junction_table)?
PostPosted: Mon May 08, 2006 2:57 pm 
Newbie

Joined: Sat May 22, 2004 4:57 pm
Posts: 9
Hibernate version:
2.1.8

Name and version of the database you are using:
PostgreSQL 7.4.x

I have three object: Role, Group, and User, linked via many-to-many relationships

Code:
Role <----> Group <-------> User
        m..n                  m..n
     (role_group)     (group_user)


I am trying to do an HQL query to get roles for a user via groups, like

Code:
from Role r
  join r.groups as theGroup
  join theGroup.users as theUser
where theUser.username = :user


This almost works, except for returning the same Role multiple times for each user if the user is in the role by virtue of membership in different groups.

If I were coding this in straight SQL, I would probably do something like
Code:
... from role where
  exists (select 1 from group_role gr
               join group g using(group_id)
               join user u using(user_id)
                where u.username=:user)


But I can't think of any way that I can reference 'group_role' in HQL, because it is a collection support table (created in @hibernate.set table="...") rather than an entity. The closest I've come is something like

Code:
from Role
  where exists (from Group g join g.users as theUser where g in elements(r.groups))


but I've found that the 'in elements(...)' results in a nested subquery that is not as scalable as going directly against the junction table would be.

Is there a way to do this in Hibernate, or is this one of those times when you should use a direct SQL query? Thanks in advance!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.