简体   繁体   English

嵌套选择的休眠条件

[英]Hibernate Criteria for nested select

I have sql select for which I want write criteria. 我有要选择其条件的sql选择。 I was googling some time, but cant find anything for "not in". 我在谷歌上搜索了一段时间,但找不到“ not in”的任何内容。 My sql query: 我的SQL查询:

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". 您选择了所有具有权限“ ROLE_ADMIN”的用户,而我需要的不是“ ROLE_ADMIN”的所有用户。 smple "not" was not working, because there are users that have "ROLE_ADMIN", and "ROLE_MODERATOR" in one time. smple“ not”不起作用,因为有些用户一次拥有“ ROLE_ADMIN”和“ ROLE_MODERATOR”。 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 您应该在Hibernate映射中将权限映射为类user的属性。

<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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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