I am trying to use subqueries in an application that I am writing using APIs such as the secure type JPA 2.0, with Hibernate 3.6.1.Final as my provider. I have no problem choosing primitive types (Long, MyEntity, etc.), but I want to select multiple columns.
Here is an example of something quite reasonable. Ignore the unnecessary use of a subquery - it just means an illustration.
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);
Although the compiler does not complain, I still get an exception at runtime.
java.lang.ClassCastException: org.hibernate.ejb.criteria.expression.CompoundSelectionImpl cannot be cast to javax.persistence.criteria.Expression
- Is this a bug in sleep mode, or am I doing something wrong?
- If you cannot use
multiselectin a subquery, then how can you perform groupBy? - If you cannot use
groupByin a subquery, why is it in the API?