gpt4 book ai didi

java - 使用 Hibernate Criteria API 查询实体不具有特定值的多对多关联

转载 作者:行者123 更新时间:2023-12-02 08:11:57 25 4
gpt4 key购买 nike

我有两个类 User 和 Role,它们使用多对多关联相互映射。现在我尝试使用 Hibernate Criteria API 查询不具有特定角色的所有用户。但我有点卡住了。

要查询具有特定角色的用户,我使用以下查询,效果很好。

Session session = getSessionFactory().getCurrentSession();          
Criteria mainCrit = session.createCriteria(boClass);
return mainCrit.createAlias("roles", "r").add( Restrictions.eq("r.name", roleName)).list();

现在我有点困惑如何反转查询并获取所有不具有特定角色的用户。如果可能的话,我想显式排除某个角色,并且不要查询用 OR 链接它们的所有角色,因为稍后可能会动态添加更多角色。

更新

为了更好地理解我的场景,您可以在another question中查看我试图查询的关联。 。

另外我还要补充一点,Role类的name属性是一个Enum,不知道这是否重要或者改变了查询数据库的方式。

最佳答案

也许有一种更优雅的方法,但我发现的唯一方法是查询具有给定角色名称的用户角色中不存在任何角色的所有用户。

这样做是这样的:

Criteria c = session.createCriteria(User.class, "user");

DetachedCriteria roleOfUserWithName = DetachedCriteria.forClass(Role.class, "role");
roleOfUserWithName.createAlias("role.users", "userOfTheRole");
roleOfUserWithName.add(Restrictions.eqProperty("userOfTheRole.id", "user.id"));
roleOfUserWithName.add(Restrictions.eq("role.name", roleName);
roleOfUserWithName.setProjection(Projections.id());

c.add(Subqueries.notExists(roleOfUserWithName));

它相当于以下 HQL 查询:

select user from User user where not exists (
select role.id from Role role inner join role.users userOfTheRole
where userOfTheRole.id = user.id
and role.name = :roleName);

关于java - 使用 Hibernate Criteria API 查询实体不具有特定值的多对多关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7235175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com