Hibernate returns a duplicate because another table has duplicate values

So, I have a Users table, a Projects table and a User_Roles table. I have one user connected to 2 projects, but when I have only one role for him, he returns these 2 projects, but if I have 2 roles for him, he returns 4 roles (2x2 projects). How to prevent this

This is my code to return a list of projects for a user

@Override
public List<Project> retrieve(User user) {
    Criteria criteria = super.createCriteria();
    criteria.addOrder(Order.desc("date"));
    criteria.createCriteria("users").add(Restrictions.eq("id", user.getId()));

    return (List<Project>) criteria.list();
}

display in user class

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Users_Projects",
           joinColumns = @JoinColumn(name = "UserID"), inverseJoinColumns =   @JoinColumn(name = "ProjectID"))
public List<Project> getProjects() {
    return projects;
} 

@ElementCollection(fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@Column(name = "RoleType")
@JoinTable(name = "User_Roles", joinColumns = @JoinColumn(name = "UserID"))
public Set<Role> getRoles() {
    return roles;
}

Any suggestions what is the problem?

Tnx

+5
source share
1 answer

"" , , , , ,

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

, - . , , , , .

fetch = FetchType.EAGER , , , , .

, sql ( ), Java sql, .

, , , criteria.setFirstResult criteria.setMaxResults, , , , .

sql-hibernate , sql, , .

+13

All Articles