【问题标题】:JPQL query help: many-to-many relationship filtered by a collectionJPQL查询帮助:由集合过滤的多对多关系
【发布时间】:2016-03-08 15:34:23
【问题描述】:

我在使用 JPQL 编写查询时遇到问题。我有两个具有多对多关系的实体:

Entity1(用户)

@Entity
public class User implements Serializable {

    @Id
    private long id;
    private String name;

    @ManyToMany()
    @JoinTable(name="users_roles", 
        joinColumns=@JoinColumn(name="user_id"),
        inverseJoinColumns=@JoinColumn(name="role_id"))
    private Set<Role> roles;
}

Entity2(角色)

@Entity
public class Role implements Serializable {
    @Id
    private long id;
    private String name;
}

想象一下,我有一个大小不同的角色列表(例如“roleA”、“roleB”、“roleC”……),并且我希望获得在此列表中具有每个角色的每个用户。在我的脑海中,它会是这样的:

select u from users u where :roles member of u.roles

据我所知,这不起作用,因为 :roles 在“成员”的左侧使用时不能成为集合。有没有办法在一个 JPQL 查询中实现这一点?如果在单个查询中不可能,那么最好的方法是什么?

谢谢

【问题讨论】:

    标签: jpql


    【解决方案1】:

    试试这个:

    select u FROM User u JOIN u.roles r WHERE r IN (:roles)
    

    【讨论】:

      猜你喜欢
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2019-01-04
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多