Reputation: 474
I've got a problem with this situation (i'll try to make it easier) - there are users in my DB with list of roles and list of statuses.
public class User implements Serializable {
@ManyToMany(cascade = CascadeType.ALL, fetch= FetchType.LAZY)
@JoinTable(name = "role_to_user",
joinColumns={@JoinColumn(name = "user_id")},
inverseJoinColumns={@JoinColumn(name = "role_id")})
private Set<Role> roles = new LinkedHashSet<Role>();
@ManyToMany(cascade = CascadeType.ALL, fetch= FetchType.LAZY)
@JoinTable(name = "status_to_user",
joinColumns={@JoinColumn(name = "user_id")},
inverseJoinColumns={@JoinColumn(name = "status_id")})
private Set<Status> statuses = new LinkedHashSet<Status>();
}
I am trying to create a hibernate criteria, which was abble to return users (after join with role table and status table) with specified roles and statuses. Something like :
return users with role = 1 or role = 2 and status = 1
I googled something and now I can create a query which returns me users only with specified roles, but not statuses.
Criteria cr = session.createCriteria(User.class)
.createCriteria("roles")
.add(Restrictions.or(Restrictions.eq("roletype", 1), Restrictions.eq("roletype", 2)));
Table user and role are connected through role_to_user table with two columns (user_id, role_id), similarly in the same way table user and status through status_to_role table
Thanks for advice :)
Upvotes: 1
Views: 23364
Reputation: 692181
Criteria cr = session.createCriteria(User.class, "user")
.createAlias("user.roles", "role", Criteria.INNER_JOIN)
.createAlias("user.statuses", "status", Criteria.LEFT_JOIN);
cr.add(Restrictions.or(
Restrictions.eq("role.roletype", 1),
Restrictions.and(
Restrictions.eq("role.roletype", 2),
Restrictions.eq("status.statusType", 1))));
Upvotes: 14