views:

195

answers:

2

Hello

I am trying to make a query with Hibernate criteria API. It looks simple but I can't get it to work. I have 2 tables. Person and Roles. Person has a set of roles. Role doesn't have any reference to Person. (i.e a guy A can be admin, user, another girl B can be only admin, etc...) I just want to to search for everyone who is doing a certain role. i,e If I select admin, I got both A and B If I select user, I got only A.

I really looked through the internet but found nothing similar. Could someone please point me out in the right direction? Thanks in advance!

Cheers

A: 

edit:

as taken from here

Imagine the case of an online shop which sells shirts. Each shirt model comes in a certain number of available sizes. You want a query to find all the shirt models with sizes over 40. In HQL, the query might be the following :

from Shirt shirt
join shirt.availableSizes size
where size.number > 40

Using the Criteria API, you use the createCriteria() to create an inner join between the two tables, as in the following example :

session.createCriteria(Shirt.class)
.createCriteria("availableSizes")
.add(Expression.gt("number", new Integer(40)))
.list();

In your case, the syntax should be something like this:

session.CreateCriteria<User>
   .CreateCriteria("Roles")
   .Add(Expression.Eq("Id", your_role_id)
   .List<User>(); (oooops, NHibernate syntax...)

Other way to do this is to add list of Users to each Role (lazy connection, so that you don't have any performance issues elsewhere) and just get your set of users from there.

Danail
A: 

Thanks Danail! I kept searching after posting here and got my problem solved

DetachedCriteria dc = new DetachedCriteria.forClass(User.class); dc.createCriteria("authorities", "code").add(Restrictions.eq("code","ROLE_ADMINISTRATOR"));

It looks similar to what you provided. Thanks again!

Buggy