views:

207

answers:

1

Lets say I have the following one-to-many relationship:

Site has many Users
User belongs to one Site

I've setup the relationship like this

class Site {
    static hasMany = [users:User]
    ...
}

and

class User {
    static belongsTo = [site:Site]
    int number
    String username
    ...
}

Basically I want to update the username for a particular User on a particular Site and return the User object. I know the Site and the new Username so I have a function that tries to lookup the corresponding connection by using a criteria builder:

class funcClass {
    User func(Site site, int number, String newUserName) {
        def results = User.createCriteria()
        results.list = {
             eq('number', number)
             site {
                 idEq(site.id)
             }
        }
        ...
        def user = results[0]
        ...
        return user
    }
}

I get an exception similar to:

groovy.lang.MissingMethodException: No signature of method: static com.myapp.Site.call() is application for arguemtns types: ( funcClass$_closure )

Is this possible with Criteria Builder? I realize I can do the query the otherway, where I build the Criteria down from Site to User, but then I have to loop through all of the Users for the Site to find the one that matches the number I was looking to update. Am I just going to have to use an HQL query?

+2  A: 

It should be

def criteria = User.createCriteria()
def users = criteria.list {
   eq('site', site)
   eq('number', number)
   maxResults(1)
}
def user = users[0]

but you can do this with a simple dynamic finder:

def user = User.findBySiteAndNumber(site, number)
Burt Beckwith
Ooo. I didn't know dynamic finders worked on objects, I thought they just worked on primitives. I can refactor a lot. Thanks!
TheBigS