0

Ok i'm wondering what is the best way to implement my scenario.

My objects are as follows:

ProjectCategory has many Projects. Projects have a ProjectStatus. ProjectStatus has a property called name and name can be either "Closed" or "Open" etc...

I'm trying to display on a page all categories and the number of opened projects for that category next to the category name.

How would I go about doing that. The problem I'm seeing is that (using grails gorm) is that by default you cannot do something like

category.findAll{ it.status.name == "Opened" }.size() 

because the objects are not loaded that deep. Now If I forced them to load, now for all categories I'm potentially loading a bunch of projects just to get the status. Wouldn't the system take a huge hit in performance the higher amount of projects you have?

The thought of creating a counter in the category and updating it every time a project status changes makes me cringe.

I must just be sleep deprived because I can't see what the proper way of doing this would be. If the way I mentioned first with the .findAll is the way to go, do I really have to worry about performance? How would I go about implementing that?

Thanks in advance for all your help.

bouboule
  • 119
  • 9

1 Answers1

1

I would use HQL. Assuming Projects belong to a ProjectCategory, you could add something like this to your ProjectCategory class:

class ProjectCategory {

    // Fields/Methods

    def getOpenedProjectsCount() {
        ProjectCategory.executeQuery("SELECT count(*) FROM Projects p WHERE p.projectCategory = :projectCategory AND p.projectStatus.name = 'Opened'", [projectCategory: this])
    }
}

Then when you have a ProjectCategory instance you can use the openedProjectsCount property:

def projectCategory = ProjectCategory.get(123)
projectCategory.openedProjectsCount
grantmcconnaughey
  • 10,130
  • 10
  • 37
  • 66
  • The problem with your approach, OP, is that it will query and create all of those objects just to do a count of them. Instead, do the count on the database. That will be much faster. – grantmcconnaughey May 29 '14 at 20:57