我有一个包含课程列表的Teacher
课程,现在我不知道如何使用hibernate criteria
和限制对这个课程列表进行过滤?
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);
}
答案 0 :(得分:0)
您需要为您的收藏集创建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());