1

我有两个表:用户和角色。一个用户可能有更多的角色,所以这是一个多对多关系。我用 Netbeans 生成了实体类,它们看起来像这样:

@Table(name = "users")
public class Users implements Serializable {
    @Id
    @Basic(optional = false)
    @Column(name = "user_name")
    private String userName;
    @JoinTable(name = "user_roles", joinColumns = {
        @JoinColumn(name = "user_name", referencedColumnName = "user_name")}, inverseJoinColumns = {
        @JoinColumn(name = "role_name", referencedColumnName = "role_name")})
    @ManyToMany(fetch = FetchType.LAZY)
    private Collection<Roles> rolesCollection;

(ETC)

@Table(name = "roles")
public class Roles implements Serializable {
    @Id
    @Basic(optional = false)
    @Column(name = "role_name")
    private String roleName;
    @ManyToMany(mappedBy = "rolesCollection", fetch = FetchType.LAZY)
    private Collection<Users> usersCollection;

这是我的问题:我想在一个表中列出所有用户,并为每个用户列出他们拥有的所有角色。我想不出解决办法。如何引用 JPQL 中的集合?如何退回收藏?这可能吗?

更糟糕的是,我有自己的类,我想用它来在我的 JSF 页面上显示结果。这是当前的查询:

Query query = em.createQuery("SELECT NEW UserListQueryObject"
        + "(u.userName, ...)"
        + " FROM Users u",
        UserListQueryObject.class);
List<UserListQueryObject> users = query.getResultList();

它适用于简单的属性和 OneToOne 关系。但不适用于多对多。我尝试像这样加入:

Query query = em.createQuery("SELECT NEW UserListQueryObject"
        + "(u.userName, ...., r.roleName)"
        + " FROM Users u JOIN u.rolesCollection r",
        UserListQueryObject.class);

... but the runtime complained about bad syntax near "r", and also about r.roleName. And it wanted to return a single role, but I need all the roles for a user!

I'm not an expert at SQL either, so it is quite possible that the solution is simple... still after having read the "Pro JPA 2..." book I'm stuck. Thanks for any help.

4

1 回答 1

0

I'd like to list all users in a table, and for each user all the roles they have. (...)

If you want to read multiple objects in a single query, you can use a join fetch:

SELECT u FROM Users u JOIN FETCH u.rolesCollection

This will perform an INNER join which means that this will filter any Users from the result set that did not have roles.

To avoid the above behavior, use an OUTER join:

SELECT u FROM Users u LEFT JOIN FETCH u.rolesCollection
于 2010-06-28T15:31:47.147 回答