休眠限制ManyToMany
问题描述:
我有一个Teacher
类,其中包含一个课程列表,现在我不知道如何使用休眠criteria
和限制过滤这个列表的课程?休眠限制ManyToMany
public class Teacher extends BaseEntity implements Serializable {
@ManyToMany(targetEntity = Course.class, fetch = FetchType.EAGER)
private Set<Course> courses;
}
public class TeacherSearchCriteria extends Criteria {
private Course course;
}
这里是我的服务类,提供了限制逻辑:
EntityManager em = getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
List<Teacher> result = Collections.EMPTY_LIST;
CriteriaQuery<Teacher> criteria = builder.createQuery(Teacher.class);
Root<Teacher> from = criteria.from(Teacher.class);
if (searchCriteria != null) {
List<Predicate> restrictions = new ArrayList<Predicate>();
if (searchCriteria.getCourse() != null) {
//Here I don't know how to make the restrictions on Set of
//courses
restrictions.add(builder.equal(from.get("courses"),
searchCriteria.getCourse()));
}
addRestrictionsToCriteria(restrictions, criteria, builder);
}
答
您需要为您收集alias。然后,您可以添加对集合中属性的限制。别名的创建告诉hibernate在构造sql时执行到表的连接。
EntityManager em = getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
List<Teacher> result = Collections.EMPTY_LIST;
CriteriaQuery<Teacher> criteria = builder.createQuery(Teacher.class);
criteria.createAlias("courses", "c")
.add(Restrictions.eq("c", searchCriteria.getCourse());
为课程创建别名,然后在限制中引用别名。我会尝试一点点发表完整的答案 –