JPA / HQL - 查找包含一个或多个特定元素的多对多关系的行

时间:2013-01-02 23:34:53

标签: java hibernate jpa hql

我有一个GrantedRole课程,允许在一个或多个Site中授予特定角色,例如:

public class GrantedRole {
    private RoleType role;

    private User granter;
    private User grantee;
    private Collection<Site> grantSites;

    @Column(nullable = false)
    public UserRoleType getRole() {
        return role;
    }

    @ManyToOne(optional = false, fetch=FetchType.LAZY)
    public User getGranter() {
        return granter;
    }

    @ManyToOne(optional = false, fetch=FetchType.LAZY)
    public User getGrantee() {
        return grantee;
    }

    @ManyToMany
    public Collection<Site> getGrantSites() {
        return grantSites;
    }
}

我想要提出的是一个查询,它会找到特定格兰特发出的GrantedRoleSitegrantSites的{​​{1}}个{ {1}}集合。如下所示:

SELECT g FROM GrantedRole g WHERE g.granter = :granter AND 
    g.grantSites [contains at least one of] (:sites) 

...但我不确定[contains at least one of]使用什么语法,或者甚至可以使用JPA / HQL。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

我能够通过调整这里找到的答案来完成这项工作:

Checking the Intersection of Two Collections via HQL

具体做法是:

SELECT DISTINCT g FROM GrantedRole g, Site s WHERE g.granter = :granter 
    AND s IN (:sites) AND s IN ELEMENTS(g.grantSites) 
    ORDER BY g.grantee.firstName ASC, g.grantee.lastName ASC