JPQL,如何不选择某些内容
我需要执行一个非常简单的 SQL。
我有一个 ProcessUser、Role 和 ProcessUserRole 表。一个简单的多对多,
我想选择所有也具有管理员角色的ProcessUser
。
但是,我的 JPQL 失败,因为我的用户也有角色负责人,因此在列表中检索到它。
这是 JPQL:
entityManager.createQuery("SELECT p FROM " + ProcessUser.class.getName()
+ " p join p.roles role WHERE role.name NOT IN ('sysadmin')").getResultList();
生成的 SQL 是:
select distinct processuse0_.id as id8_, processuse0_.position as position8_, processuse0_.username as username8_, processuse0_.organization_id as organiza9_8_, processuse0_.passwordHash as password4_8_, processuse0_.fromEmail as fromEmail8_, processuse0_.firstname as firstname8_, processuse0_.lastname as lastname8_, processuse0_.processes as processes8_ from ProcessUser processuse0_ inner join ProcessUserRoles roles1_ on processuse0_.id=roles1_.userId inner join Role role2_ on roles1_.roleId=role2_.id where ( role2_.name not in ( 'sysadmin' ) )
I have a pretty simple SQL I need to perform.
I have a ProcessUser
, Role
and a ProcessUserRole
table. A straight forward many-to-many
I want to select all ProcessUser
's that does also have a Role of admin.
However my JPQL fails because my user also has role officer, so it is retrieved in the list.
Here is the JPQL:
entityManager.createQuery("SELECT p FROM " + ProcessUser.class.getName()
+ " p join p.roles role WHERE role.name NOT IN ('sysadmin')").getResultList();
The generated SQL is:
select distinct processuse0_.id as id8_, processuse0_.position as position8_, processuse0_.username as username8_, processuse0_.organization_id as organiza9_8_, processuse0_.passwordHash as password4_8_, processuse0_.fromEmail as fromEmail8_, processuse0_.firstname as firstname8_, processuse0_.lastname as lastname8_, processuse0_.processes as processes8_ from ProcessUser processuse0_ inner join ProcessUserRoles roles1_ on processuse0_.id=roles1_.userId inner join Role role2_ on roles1_.roleId=role2_.id where ( role2_.name not in ( 'sysadmin' ) )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用子查询的正确 JPQL 语法:
Proper JPQL syntax using subquery:
这对你有用吗?
Will this work for you?
您的查询基本上是带回用户/角色列表,因为您的用户有两个角色,他回来了两次,您通过排除“sysadmin”角色来过滤掉一行。听起来您想要做的是排除所有具有“sysadmin”角色的用户,无论他们具有其他角色。您需要在查询中添加一些内容,例如。 (我会根据您的查询而不是您的描述)
Your query is basicly bringing back a list of user/roles since your user has two roles he comes back twice, you filter out one row by excluding the role of 'sysadmin'. What it sounds like you want to do is exclude all users who have a role of 'sysadmin' regardless of they have other roles. You would need to add something to you query like. (I'm going by your query not your description)
运行嵌套查询。首先选择具有 sysadmin 角色的所有用户。然后选择该结果的补充,或不在此结果中的所有用户。
Run a nested query. First select all users with the role of sysadmin. Then select the complement of this, or all users that are not in this result.
JPQL:
JPQL: