开发者

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 joi开发者_如何学JAVAn 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜