2011-11-27 86 views
1

我在休眠 像@ManyToMany關係: 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); 
} 

表角色:

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

如何讓全體員工當角色被休眠有一個特定的值標準 或子查詢

回答

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(); 
3

如果我understan ð正確的,你想獲得具有特定角色的所有員工。爲什麼要使用標準的API爲這一點。 HQL更簡單,可讀:

​​

如果你真的想使用Criteria API,這裏有雲: