最近原Hibernate項目須要添加一個條件,結構有點相似下面的格式,學生和房間是多對一的關係,如今要查詢全部沒有房間的學生。java
Class Student{post
@ManyToOneui
Room room;
}spa
一開始的查詢語句是這樣的:rest
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);
發現項目查詢時會報錯,最後查詢文檔http://www.objectdb.com/java/jpa/query/jpql/literal#Criteria_Query_Literals_code
發如今JPA動態查詢時,條件全是Expression類型blog
因此不能直接使用null,而須要把null轉換成Expression類型,語句以下:文檔
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("room"), criteriaBuilder.nullLiteral(Room.class)));
修改完查詢正常