2

I have two tables(entities):

@Entity
@Table(name = "users")
@NamedQuery(name = "User.getAll", query = "SELECT c from User c")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @NotNull
    @Column(name = "LOGIN")
    private String login;

    @Column(name = "PASSWORD", length = 64)
    private String password;

    @Column(name = "SALT", length = 80)
    private String salt;

    @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
    private Set<Role> roles;

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Permission> permissions;

And

@Entity
@Table(name = "roles")
@NamedQuery(name = "Role.getAll", query = "SELECT c from Role c")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "ROLE_NAME", length = 100)
    private String roleName;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users;

And method for select Users:

@Override
    public List<User> getUsersList() {
        Criteria criteria = getSession().createCriteria(User.class);
        return (List<User>)criteria.list();
    }

I have 2 users. First user has 2 roles and second user has 1 role. But this method return me 3 users. User who has 2 role is dublicate.

Itried criteria.createCriteria("", JoinType.NONE);

but it not helped.

user5620472
  • 2,722
  • 8
  • 44
  • 97

1 Answers1

1

You need to use criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY), check: criteria-distinct-root-entity-vs-projections-distinct

Community
  • 1
  • 1
Mooolo
  • 428
  • 2
  • 7