最近原Hibernate项目需要添加一个条件,结构有点类似下面的格式,学生和房间是多对一的关系,现在要查询所有没有房间的学生。
Class Student{
@ManyToOne
Room room;
}
一开始的查询语句是这样的:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class); Root<Student> root = criteriaQuery.from(Order.class); criteriaQuery.select(root); //多条件查询 Predicate restrictions = criteriaBuilder.conjunction(); //组合条件 restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("room"), null)); //将条件添加到查询 criteriaQuery.where(restrictions);