I have two entities, Ablum and Image, which are in many to many relationship.
I wanna make a criteria query that to get all Albums and the counts on how many Images they have.
I don’t want to get all Albums first then loop the result to get the counts as there would be so many sql requests.
I’ve been working for 2 nights and complete lost. If cannot find a way out maybe I need to fallback to use SQL.
I have two entities, Ablum and Image, which are in many to many relationship.
Share
Thanks to digitaljoel’s inspiration, I found that CriteriaBuilder has a method call “size” that can be put on collections. Below is the code:
Here the groupBy call is a must otherwise error will occur.
But this method is to load the IDs of AlbumEntity, not the entity itself. The Album entity can be load if below code is used:
The groupBy must include all properites of the album entity. And it still does not work if the album entity has blob type property.