具有两个角色的一个用户的输出

I have two entities User and Role. They have a unidirectional ManyToMany connection. But when calling the list of Users, for some reason the User is returned several times with several roles.

下面我提供了代码和结果。

结果

new pic

Дебаг

new pic

使用HQL查询进行编码
 public List<User> listUsers() {
     List resultList = manager.createQuery("SELECT u FROM User u LEFT JOIN FETCH u.roles").getResultList();
     return resultList;
 }

UPD:

我找到了这个解决方案:

public List<User> listUsers() {
    List resultList = manager.createQuery("SELECT u FROM User u LEFT JOIN FETCH u.roles")
            .unwrap(org.hibernate.Query.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .getResultList();
    return resultList;
}

But the criteria API is slow, it is not recommended to use it, and it is deprecated.

如何显示一个具有两个角色的用户???

评论