简体   繁体   English

Output 一个用户有两个角色

[英]Output of one user with two roles

I have two entities User and Role .我有两个实体UserRole They have a unidirectional ManyToMany connection.它们具有单向ManyToMany连接。 But when calling the list of Users, for some reason the User is returned several times with several roles.但是当调用用户列表时,由于某种原因,用户多次返回多个角色。

Below I have provided the code and the result.下面我提供了代码和结果。

Result结果

新图片

Дебаг Дебаг

新图片

Code with HQL queries带有 HQL 查询的代码

 public List<User> listUsers() {
     List resultList = manager.createQuery("SELECT u FROM User u LEFT JOIN FETCH u.roles").getResultList();
     return resultList;
 }

UPD:升级版:

I found this solution:我找到了这个解决方案:

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.但是criteria API比较慢,不推荐使用,已弃用。

How do I display one user with two roles???如何显示一个用户有两个角色???

Need to add a distinct statement in your query to avoid multiple entries需要在查询中添加distinct的语句以避免多个条目

 public List<User> listUsers() {
     List resultList = manager.createQuery("SELECT distinct u FROM User u LEFT JOIN FETCH u.roles").getResultList();
     return resultList;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM