条件 api - illegalStateException

Criteria api - illegalStateException

我使用 Criteria Api:

编写了以下代码
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

CriteriaQuery<Entity> criteriaQuery = criteriaBuilder.createQuery(Entity.class);
Root<Entity> root = criteriaQuery.from(Entity.class);
criteriaQuery.select(root);

CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
countQuery.select(criteriaBuilder.count(root));

Long countOfRows = entityManager.createQuery(countQuery).getSingleResult();

结果我得到一个异常:

java.lang.IllegalStateException: No criteria query roots were specified

异常是由getSingleResult方法抛出的(代码的最后一行)。谢谢你的帮助!

强制countQuery添加root后有效:

((QueryStructure)((CriteriaQueryImpl)countQuery).queryStructure).roots.add(root)