【问题标题】:How to get entities that have a collection and one element of this collection in another collection如何在另一个集合中获取具有集合和该集合的一个元素的实体
【发布时间】:2013-05-28 00:35:01
【问题描述】:

现在我正在尝试实现过滤器之类的功能。有两个模型用户和角色。我使用单向多对多关系。下面是我的代码。

    public class User {
        ...
        @ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
        @JoinTable(name = "user_role", joinColumns = {@JoinColumn(name="user_id") }, 
        inverseJoinColumns = { @JoinColumn(name = "role_id") })
        private Set<Role> roles = new HashSet<Role>();
        ...
    }

    public class Role {
        private String role;
        ...
    }

现在我想获取具有许多角色的用户,但在用户被挑选出来的角色集合中恰好只是其中一个用户的角色。我想使用 HQL 进行查询,但我不知道怎么做,所以我写了一个 sql "select * from user as u left join user_role as ur on u.id = ur.user_id where ur.role_id in (1,2)"。但是结果无法转换为用户列表。我仍然需要使用 HQL,所以任何人都可以提供一些帮助。谢谢。

【问题讨论】:

    标签: many-to-many hql jointable


    【解决方案1】:

    你的 SQL 查询的翻译是

    select u from User u join u.roles role 
    where role.id in (1,2)
    

    请参阅the documentation 了解 HQL 和联接。

    【讨论】:

    • 非常感谢!根据您的建议,我解决了这个问题:“从用户中选择不同的 u 加入 u.roles 角色,角色 ID 在 (2,3) 中”
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多