I am trying, as in the header, to insert a subquery into the select clause, as in this simple SQL:
SELECT id, name, (select count(*) from item) from item
this is obviously just a mock request to make my point. (The point is to get the last count for each item returned by the request.)
I tried this:
CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Tuple> c = cb.createTupleQuery(); Root<Item> item= c.from(Item.class); Subquery<Long> scount = c.subquery(Long.class); Root<Item> sarticolo = scount.from(Item.class); scount.select(cb.count(sitem)); c.multiselect(item.get("id"),item.get("nome"), scount); Query q = em.createQuery(c); q.setMaxResults(100); List<Tuple> result = q.getResultList(); for(Tuple t: result){ System.out.println(t.get(0) + ", " + t.get(1) + ", " + t.get(2)); }
but I only get:
java.lang.IllegalStateException: Subquery cannot occur in select clause
How can I get a similar result?
select subquery jpa criteria
lelmarir
source share