I have an application used for rating items. Each item has a zero-to-many logical relationship to a rating. (Each rating is associated to exactly one item and one user). A user can pick an
item and then give it a rating between 0 and 3. Whenever I retrieve an item (or all items) I want to populate each Item object with the number of times it has been rated, and the sum of all the ratings. Currently I am retrieving the ratings for each item via a one-to-many mapping. Then I derive the numItems and totalRating values by looping through the set of ratings. This seems rather heavyweight and I am afraid it won't scale. Another option is to let the DB calc these values via HQL like the folloing:
Code:
select count(itemRating), sum(itemRating.value) from itemRating
The problem is I want to retrieve these values everytime I get the items. I was thinking I could use a join like:
Code:
select item, count(itemRating), sum(itemRating.value) from Item item, ItemRating itemRating where itemRating.item.id = item.id
The problem is that this forces me to manually walk thru the resulting list manually setting the number of ratings (the count), and total ratings (the sum) for each item -- this seems cumbersome. Is there a better way of doing this. Maybe it would be better to load the properties using 2 selects -- one for all items, and the other for all itemRatings -- however, this still forces me to merge the results in the middle-tier which I was trying to avoid. Anyone have any better ideas?