I have @manytomany relation in hibernate Like : Table Employee
public class Employee implements Serializable {
@ManyToMany(fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
@JoinTable(name = "employee_role", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
private Set<Role> roles = new HashSet<Role>(0);
}
Table Role :
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "role_id", unique = true, nullable = false)
@Basic(fetch = FetchType.EAGER)
private long id;
}
how to get all employee when role have a specific value by hibernate Criterion or subquery
If I understand correctly, you want to get all employees having a specific role. Why use the Criteria API for this. HQL is much simpler and readable:
select e from Employee e inner join e.roles role where role.id = :roleId
If you really want to use the Criteria API, here it goes:
Criteria c = session.createCriteria(Employee.class, "employee");
c.createAlias("employee.roles", "role");
c.add(Restrictions.eq("role.id", roleId));
List<Employee> employeed = c.list();
the try JB Nizet's answer and return multiple row not the same number in table the solution is to add setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
Criteria c = getCurrentSession().createCriteria(Employee.class,"employee");
c.createAlias("employee.roles", "role");
c.add(Restrictions.eq("role.id", id));
List<Employee> employeed = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.