Question

I have query in Criteria API, that goes like this:

CriteriaQuery<XXX> query = builder.get().createQuery(XXX.class).distinct(true);
Root<XXX> root = query.from(XXX.class);
Fetch<XXX, YYY> fetch = root.fetch(XXX_.yyy, JoinType.LEFT);

now the part I'm stuck on:
when I got query results, I got list of XXX records, with attached list of YYY records, when they exist.
I want to sort my result by NUMBER OF YYY records atatched to XXX object.

And so far, I'm closer to paranoia then to that goal. Anyone?

Was it helpful?

Solution

To solve you problem you need to get in result SQL Query(which is generated from hibernate criteria) that will look like this:

SELECT xxx.*,count(yyy.FOREIGN_KEY_FIELD) as count FROM XXX xxx left join YYY yyy on (yyy.FOREIGN_KEY_FIELD=xxx.PRIMARY_KEY_FIELD) group by xxx.PRIMARY_KEY_FIELD order by count

Probably for this case you need to use hibernate query api. Criteria is created for Entities and return only list of entities and some projections. In hql it will look very similar to:

select xxx,count(yyy.FOREIGN_KEY_FIELD) as count from XXX xxx left join xxx.yyy yyy group by xxx.PRIMARY_KEY_FIELD order by count

HQL is more flexible for such queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top