I'm using Hibernate 5.2.8 with JPA, no Spring or anything like that. As I'm sure you're familiar, in order to get a total count of objects, a CriteriaQuery<Long> needs to be created. Since I've already written an entire CrtieriaQuery with an existing root / joins / predicates, and since changing the type of an existing CriteriaQuery is a no-no, it'd be great if I could just create a new CriteriaQuery re-using the join chain and conditions that I've already created:
Code:
CriteriaQuery<Long> cntQuery = cb.createQuery(Long.class);
TypedQuery<Long> cntQ = em.createQuery(
cntQuery.select(
cb.count(root))
.where(predicates));
Of course, this won't work because cntQ needs a .from() on it, pointing to a new root (since the root apparently can't be inferred simply from what's being counted?....)
But then, if I need to point cntQ to a new root, I would need to also create new joins on that root to satisfy all my predicates...
And then, if I create new joins, I have to create new predicates based on all those joins...
...and the result is just a big mess of code duplication could have been avoided by sticking with simple string splicing (i.e. just re-use a stringified FROM clause). I could break out the creation of those joins and their predicates into a separate method that is called when constructing both the count and list queries, but this would just bring things to a whole new apex of unintelligibility. So I would need to just duplicate code in order for other devs to be able to interpret this easily at all.
Unfortunately, that code duplication, not to mention the extra CPU used in translating from the criteria API to JPQL, means I'm better off going back to string splicing rather than using the criteria API. I really hope I'm wrong. What can be done about this?