Recently, the original Hibernate project needs to add a condition, the structure is somewhat similar to the following format, the relationship between students and rooms is many-to-one, and now all students without rooms need to be queried.
Class Student{
@ManyToOne
Room room;
}
The initial query statement is as follows:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class); Root<Student> root = criteriaQuery.from(Order.class); criteriaQuery.select(root); // Multiple criteria query Predicate restrictions = criteriaBuilder.conjunction(); // Combination criteria restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("room"), null)); // Add criteria to query criteriaQuery.where(restrictions);
An error will be reported when the project query is found, and finally the document is queried http://www.objectdb.com/java/jpa/query/jpql/literal#Criteria_Query_Literals_
It is found that in the JPA dynamic query, the conditions are all Expression types
So you can't use null directly, but you need to convert null to Expression type, the statement is as follows:
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("room"), criteriaBuilder.nullLiteral(Room.class)));
the query is normal after modification