manytomany检索标准

时间:2011-11-27 14:38:50

标签: java hibernate jpa

我在hibernate中有@manytomany关系 喜欢 : 表员工

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);
}

表格角色:

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

如何通过 hibernate Criterion 在角色具有特定值时获得所有员工 或子查询

2 个答案:

答案 0 :(得分:3)

如果我理解正确,您希望让所有员工都具有特定的角色。为什么要使用Criteria API。 HQL更简单易读:

select e from Employee e inner join e.roles role where role.id = :roleId

如果您真的想使用Criteria API,请点击此处:

Criteria c = session.createCriteria(Employee.class, "employee");
c.createAlias("employee.roles", "role");
c.add(Restrictions.eq("role.id", roleId));
List<Employee> employeed = c.list();

答案 1 :(得分:0)

尝试JB Nizet的回答并在表中返回多行不同的数字 解决方案是添加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();