2

I am using Spring with Hibernate in my project. I want to get users by a particular role using Hibernate criteria. My User model is connected with Role model using @ManyToMany annotation:

@ManyToMany(fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
@JoinTable(
        name = "user_role",
        joinColumns = {@JoinColumn(name = "user_id")},
        inverseJoinColumns = @JoinColumn(name = "role_id")
)
public Set<Role> getRoles() {
    return roles;
}

and here is my criteria in my UserDaoHibernate:

public List<User> getUsersByRole(List<Role> roles) {
    List users = getSession().createCriteria(User.class)
            .add(Restrictions.in("roles", roles)).list();
    return users;
}

I am getting DataIntegrityViolationException when executing this criteria. Am i missing something or is there any correct way of getting users by their roles?

JIT Develop
  • 128
  • 1
  • 10
  • 1
    Try to check [this](http://stackoverflow.com/a/20427782/1679310) and also [this](http://stackoverflow.com/a/26718407/1679310) for some more ideas about many-to-many querying – Radim Köhler Dec 10 '14 at 05:48
  • Can You please tell me what is wrong with my criteria? – JIT Develop Dec 11 '14 at 05:06
  • 1
    In general, you've used many-to-many, which is very difficult to use for querying. I tried to explain that many times: http://stackoverflow.com/q/15510748/1679310. If you will use many-to-one, your searching will becom more simple and you can use this simple approach: http://stackoverflow.com/q/20426734/1679310 – Radim Köhler Dec 11 '14 at 07:03

2 Answers2

0

I have finally figured it out by following the trigger in the comment and this answer here

This solution is not completely solve the problem as it intends to get only users by one role, for example.

Community
  • 1
  • 1
JIT Develop
  • 128
  • 1
  • 10
0

Maybe I misunderstood you, but this method works for me:

List<User> findUsersByRoles_RoleIdIn(List<Integer> roles);