我试图在我正在使用JPA 2.0类型安全标准API编写的应用程序中使用子查询,Hibernate 3.6.1.Final作为我的提供者.我没有选择原始类型(Long,MyEntity等)的问题,但我想选择多个列.
这是一个完全合理的例子.忽略子查询的不必要使用 – 它仅仅是说明性的.
EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = cb.createTupleQuery(); Subquery<Tuple> subQ = cq.subquery(Tuple.class); Expression<Long> subqCount; { Root<MyEntity> root = subQ.from(MyEntity.class); Path<MyEntity> filter = root.get(MyEntity.challenge); subqCount = cb.count(root); // How to select tuple? Selection<Tuple> tuple = cb.tuple(filter,subqCount); // !! Run-time exception here Expression<Tuple> tupleExpr = (Expression<Tuple>) tuple; // Not sure why I can't use multiSelect on a subQuery // #select only accepts Expression<Tuple> createSubQ.select(tupleExpr); createSubQ.groupBy(filter); } cq.multiselect(subqCount);
虽然编译器没有抱怨,但我仍然遇到运行时异常.
java.lang.ClassCastException: org.hibernate.ejb.criteria.expression.CompoundSelectionImpl cannot be cast to javax.persistence.criteria.Expression
>这是休眠中的错误,还是我做错了什么?
>如果您不能在子查询上使用多选,那么如何执行groupBy?
>如果您不能在子查询上使用groupBy,为什么它在API中?