简体   繁体   中英

Hibernate Criteria for nested select

I have sql select for which I want write criteria. I was googling some time, but cant find anything for "not in". My sql query:

select * from users where username not in(
select users.username from users right join authorities on users.username=authorities.username 
where authority='ROLE_ADMIN')  

Thanks a lot in advance. Regards, Mat

Thanks for the answer, but it's not exactly like this. You selected all the users with authority "ROLE_ADMIN", and I needed all the users that are not "ROLE_ADMIN". smple "not" was not working, because there are users that have "ROLE_ADMIN", and "ROLE_MODERATOR" in one time. I managed to solve it like this:

DetachedCriteria subCriteria = DetachedCriteria.forClass(Authorities.class);
subCriteria.add(Property.forName("authority").ne(authorityName));
subCriteria.setProjection(Projections.property("users"));

DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
criteria.add(Property.forName("username").notIn(subCriteria));
return getHibernateTemplate().findByCriteria(criteria);

It works, but do you think it's a good solution?

You should map the authority as a property of class user in your Hibernate mapping

<many-to-one name="authority" class="Authority" column="AUTHORITY_ID"

After that it's easy to build the criteria query:

List users = sess.createCriteria(User.class)
.createCriteria("authority")
.add( Restrictions.eq("authority_name", "ROLE_ADMIN") )
.list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM