-->
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: Criteria equivalent for HQL ManyToMany join
PostPosted: Thu Oct 20, 2011 5:34 am 
Newbie

Joined: Thu Oct 20, 2011 5:03 am
Posts: 1
Hey there!

This is what my classes and associations look like
Code:
class User {
    @Id
    long id;
    @ManyToMany
    Set<Role> roles;
}

class Role {
    @Id
    Long id;
    String name;
    @ManyToMany(mappedBy="roles")
    Set<User> users;
}


Now I need to query a User's Roles and do some sorting. My HQL query is
Code:
SELECT r FROM User u JOIN u.roles r WHERE u.id = :uid ORDER BY r.name

This returns what I want, however ..

Hibernate creates the following SQL query
Code:
select role2_.ROLE_ID as ROL1_4_, role2_.NAME as NAME4_ from USERS user0_ inner join USERS_ROLES roles1_ on user0_.USER_ID=roles1_.USER_ID inner join ROLES role2_ on roles1_.ROLE_ID=role2_.ROLE_ID where user0_.USER_ID=? order by role2_.NAME


Bear with me, I'm rather new to SQL itself as well. The following SQL query seems to be more efficient
Code:
SELECT role_id, name FROM roles WHERE role_id IN (SELECT role_id FROM users_roles WHERE user_id=?) ORDER BY name;


So my question is twofold; How would I achieve the same (i.e. selecting and sorting a User's Roles) with pure Criteria API? If there is no way, how would I create a more efficient HQL query?


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.