user5620472 user5620472 - 4 years ago 142
Java Question

How corectly select entity with ManyToMany realationship in Hibernate jpa

I have two tables(entities):

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

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

@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;


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

@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:

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.

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

but it not helped.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download